/**
	* \file			ROMListScreen.cpp
	* \brief		Helper class which takes care of generating/loading/displaying
	*           a list of all available ROMs
	*/

//= I N C L U D E S ====================================================
#include "ROMListScreen.h"
#include "DebugLogger.h"
#include "XBFont.h"
#include "xmvhelper.h"

#include "xbox_FileIO.h"		// for path info
#include "xbox_Direct3DRenderer.h" // For Set/GetScreenUsage
#include "smbhandler.h"
#include "System_IniFile.h"

#include <string>
#include <vector>
#include <algorithm>

extern "C" {
#include "osdepend.h"
#include "driver.h"
}

//= S T R U C T U R E S ===============================================

//= D E F I N E S ======================================================

//= G L O B A L = V A R S ==============================================
  // Static member initialization
MAMEDriverData_t                        *CROMListScreen::m_driverInfoList = NULL;
UINT32                                  CROMListScreen::m_numDrivers = 0;
std::vector<ROMStatus>                  CROMListScreen::m_ROMStatus;
std::vector<MAMEoXDriverMetadata_t>     CROMListScreen::m_driverMetadata;
extern BOOL g_soundEnabled;

extern IDirect3DDevice8 *Device;
extern bool initMovie(char*);
extern void stopMovie();
extern void drawMovie();
extern bool videoRender;

extern float fLeft;
extern float fRight;
extern float fTop;
extern float fBottom;  // Ken Video Support
BOOL         m_FastScroll; 
BOOL         m_ForcePic; 
BOOL         m_Random; 

//= P R O T O T Y P E S ================================================
extern "C" void DrawProgressbarMessage( LPDIRECT3DDEVICE8 pD3DDevice, const char *message, const char *itemName, DWORD currentItem, DWORD totalItems ); // Defined in main.cpp


  // Compare functions for ROM List sorting
static BOOL Compare_Description( UINT32 a, UINT32 b );
static BOOL Compare_Manufacturer( UINT32 a, UINT32 b );
static BOOL Compare_Year( UINT32 a, UINT32 b );
static BOOL Compare_ParentROM( UINT32 a, UINT32 b );
static BOOL Compare_Genre( UINT32 a, UINT32 b );
static BOOL Compare_NumPlayers( UINT32 a, UINT32 b );
static BOOL Compare_ROMStatus( UINT32 a, UINT32 b );
static BOOL Compare_FavoriteStatus( UINT32 a, UINT32 b );
static BOOL Compare_NumTimesPlayed( UINT32 a, UINT32 b );

static BOOL Helper_ReadXMLTag( osd_file *file, CStdString *tagName );

//= F U N C T I O N S ==================================================

//---------------------------------------------------------------------
//	LoadROMList
//---------------------------------------------------------------------
BOOL CROMListScreen::LoadROMList( BOOL bGenerate, BOOL allowClones )
{
//	PRINTMSG(( T_TRACE, "LoadROMList" ));

  m_maxPageSize = 15;
	m_ROMListFull.clear();
  m_ROMListFiltered.clear();

//	m_displayDevice->Clear(	0L,																// Count
//													NULL,															// Rects to clear
//													D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,	// Flags
//													D3DCOLOR_XRGB(0,0,0),							// Color
//													1.0f,															// Z
//													0L );															// Stencil
//	m_fontSet.DefaultFont().Begin();
//	  m_fontSet.DefaultFont().DrawText( 320, 230, D3DCOLOR_RGBA( 255, 255, 255, 255 ), L" ", XBFONT_CENTER_X );
//  m_fontSet.DefaultFont().End();
//
//	m_displayDevice->Present( NULL, NULL, NULL, NULL );	


  if( LoadROMListFile() )
  {

    UpdateSortedList();

	  
    m_numLinesInList = m_currentSortedList.size();
    return TRUE;
  }
  else if( bGenerate )
    return GenerateROMList();


  return FALSE;
}

//---------------------------------------------------------------------
//	GenerateROMList
//---------------------------------------------------------------------
BOOL CROMListScreen::GenerateROMList( void )
{
	PRINTMSG(( T_TRACE, "GenerateROMList" ));

  m_shouldGenerateROMList = FALSE;
	m_ROMListFull.clear();
  m_ROMListFiltered.clear();

  g_FileIOConfig.m_romPath0.MakeLower();
  g_FileIOConfig.m_romPath1.MakeLower();
  g_FileIOConfig.m_romPath2.MakeLower();
  g_FileIOConfig.m_romPath3.MakeLower();

	PRINTMSG(( T_INFO, "Finding files %s\\*.zip", g_FileIOConfig.m_romPath0.c_str() ));
  Helper_GenerateROMList( g_FileIOConfig.m_romPath0 );

  if( g_FileIOConfig.m_romPath1 != g_FileIOConfig.m_romPath0 )
  {
	  PRINTMSG(( T_INFO, "Finding files %s\\*.zip", g_FileIOConfig.m_romPath1.c_str() ));
    Helper_GenerateROMList( g_FileIOConfig.m_romPath1 );
  }

  if( g_FileIOConfig.m_romPath2 != g_FileIOConfig.m_romPath1 &&
      g_FileIOConfig.m_romPath2 != g_FileIOConfig.m_romPath0 )
  {
	  PRINTMSG(( T_INFO, "Finding files %s\\*.zip", g_FileIOConfig.m_romPath2.c_str() ));
    Helper_GenerateROMList( g_FileIOConfig.m_romPath2 );
  }

  if( g_FileIOConfig.m_romPath3 != g_FileIOConfig.m_romPath2 &&
      g_FileIOConfig.m_romPath3 != g_FileIOConfig.m_romPath1 &&
      g_FileIOConfig.m_romPath3 != g_FileIOConfig.m_romPath0 )
  {
	  PRINTMSG(( T_INFO, "Finding files %s\\*.zip", g_FileIOConfig.m_romPath3.c_str() ));
    Helper_GenerateROMList( g_FileIOConfig.m_romPath3 );
  }

    // Load the XML status file
  LoadROMStatusFile();
  LoadROMMetadataFile();
  ImportCatverINI();

  if( !SaveROMListFile() )
  {
    PRINTMSG(( T_INFO, "Failed to store the ROM list file!" ));
    return FALSE;
  }

    // Create the superscroll jump table
  UpdateSortedList();
  m_numLinesInList = m_currentSortedList.size();

  			   g_rendererOptions.m_fastsave = false;
			   SaveOptions();
               SaveROMMetadataFile();

  return TRUE;
}

//---------------------------------------------------------------------
//	Helper_GenerateROMList
//---------------------------------------------------------------------
BOOL CROMListScreen::Helper_GenerateROMList( CStdString &path )
{
	std::vector< CStdString > zipFileNames;
	WIN32_FIND_DATA findData;

    // Hacks for the ROM-less PatchMAME games
  static BOOL pongAdded = FALSE;

    // Check if the rom path is on a smb share
  if( path.Left(6) == "smb://")
  {
    CSMBHandler smbHandler;
    smbHandler.GetDirectory(path, ".zip", zipFileNames, TRUE);
  }
  else
  {
    HANDLE findHandle = FindFirstFile( (path + "\\*").c_str(),
                                        &findData );
    if( findHandle == INVALID_HANDLE_VALUE )
    {
      PRINTMSG(( T_INFO, "Could not find files!" ));
      return TRUE;  // This is not really an error
    }

    DWORD i = 0;
    for( ; ; ++i )
    {
        // Notify the user that a new zip has been found
        // Only redraw every 4th ROM, as rendering takes up
        // the vast majority of the overall time
      if( !(i & 0x03) )
        DrawProgressbarMessage( m_displayDevice, 
                                "Searching For Games...", 
                                findData.cFileName, 
                                i, 
                                0 );

      // Remove the extension
      CStdString filename = findData.cFileName;
      filename.ToLower();

      INT32 extensionIDX = filename.Find( ".zip" );
      if( extensionIDX != -1 )
      {
        filename = filename.Left( extensionIDX );
        zipFileNames.push_back( filename );
      }
      if( !FindNextFile( findHandle, &findData ) )
        break;
    }

    FindClose( findHandle );
  }

	PRINTMSG(( T_INFO, "Found %lu zip files!", zipFileNames.size() ));

  // Check the zip files against the list of all known zip files
	for(DWORD i = 0; i < m_numDrivers && zipFileNames.size(); ++i )
	{
      // Only redraw every 8th ROM, as rendering takes up
      // the vast majority of the overall time
    if( !(i & 0x07) )
    {
      DrawProgressbarMessage( m_displayDevice, 
                              "Checking Against Known Games...",
                              m_driverInfoList[i].m_romFileName, 
                              i, 
                              m_numDrivers );
    }

    CStdString driverFileName = m_driverInfoList[i].m_romFileName;
    driverFileName.ToLower();


      // Special handling for PatchMAME's ROM-less games
    if( !pongAdded && driverFileName == "pong" )    
    {
      pongAdded = TRUE;
      m_ROMListFull.push_back( i );
    }
    else
    {
        // Standard handling
      std::vector<CStdString>::iterator it = std::find( zipFileNames.begin(), 
                                                        zipFileNames.end(), 
                                                        driverFileName );

      if( it != zipFileNames.end() )
      {
        if( std::find( m_ROMListFull.begin(), m_ROMListFull.end(), i ) == m_ROMListFull.end() )
          m_ROMListFull.push_back( i );

        zipFileNames.erase( it );
      }
    }
	}

	PRINTMSG(( T_INFO, "Found %lu games!", m_ROMListFull.size() ));

	return TRUE;
}

//-------------------------------------------------------------
//  SaveROMListFile
//-------------------------------------------------------------
BOOL CROMListScreen::SaveROMListFile( void )
{
		// Write the indices to the ROM list file
	CStdString romListFile = DEFAULT_MAMEOXSYSTEMPATH "\\" ROMLISTFILENAME;
	PRINTMSG(( T_INFO, "Store ROM list: %s", romListFile.c_str() ));


  osd_file *file = osd_fopen( FILETYPE_MAMEOX_SYSTEM, 0, ROMLISTFILENAME, "w" );
	if( !file )
	{
		PRINTMSG(( T_ERROR, "Could not create file %s!", romListFile.c_str() ));
		return FALSE;
	}

    // Sign the file
  if( osd_fwrite( file, DRIVERLIST_FILESTAMP, sizeof(DRIVERLIST_FILESTAMP) - 1 ) != sizeof(DRIVERLIST_FILESTAMP) - 1 )
	{
		PRINTMSG(( T_ERROR, "Write failed!" ));
		osd_fclose( file );

			// Delete the file
		DeleteFile( romListFile.c_str() );
		return FALSE;
	}


    // Calculate a signature for the list, so we can validate it when reading
    //  to eliminate corrupt data
  HANDLE sigHandle = XCalculateSignatureBegin( XCALCSIG_FLAG_SAVE_GAME );
  if( sigHandle == INVALID_HANDLE_VALUE )
  {
    osd_fclose( file );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not calculate driver list signature!" ));
    return FALSE;
  }

  DWORD sigSize = XCalculateSignatureGetSize( XCALCSIG_FLAG_SAVE_GAME );
  void *sigData = calloc( 1, sigSize );
  if( !sigData )
  {
    osd_fclose( file );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not allocate memory for driver list signature!" ));
    return FALSE;
  }

    // Write in a blank signature
  if( osd_fwrite( file, sigData, sigSize ) != sigSize )
  {
    free( sigData );
    osd_fclose( file );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed writing blank signature!" ));
    return FALSE;
  }



    // Define a macro to write a block of data and calculate the data signature
  #define WRITEDATA( _data__, _dataSize__ ) \
    if( XCalculateSignatureUpdate( sigHandle, (const BYTE *)(_data__), (_dataSize__) ) != ERROR_SUCCESS || \
        osd_fwrite( file, (_data__), (_dataSize__) ) != (_dataSize__) ) \
    { \
      PRINTMSG(( T_ERROR, "Write failed!" )); \
      free( sigData ); \
      osd_fclose( file ); \
      DeleteFile( romListFile.c_str() ); \
      return FALSE; \
    }


    // Write the number of indices
  DWORD numROMs = m_ROMListFull.size();
  WRITEDATA( &numROMs, sizeof(numROMs) );

    // Write the indices
	std::vector<UINT32>::iterator it = m_ROMListFull.begin();
	for( ; it != m_ROMListFull.end(); ++it )
	{
		DWORD val = (*it);
    WRITEDATA( &val, sizeof(val) );

      // Write the ROM status
    val = (DWORD)m_ROMStatus[(*it)];
    WRITEDATA( &val, sizeof(val) );
	}

    // Grab the signature
  if( XCalculateSignatureEnd( sigHandle, sigData ) != ERROR_SUCCESS )
  {
    free( sigData );
    osd_fclose( file );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed getting signature!" ));
    return FALSE;
  }

    // Write in the real signature
  osd_fseek( file, sizeof(DRIVERLIST_FILESTAMP) - 1, SEEK_SET );
  if( osd_fwrite( file, sigData, sigSize ) != sigSize )
  {
    free( sigData );
    osd_fclose( file );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed writing signature!" ));
    return FALSE;
  }

  free( sigData );
	osd_fclose( file );
  return TRUE;
}


//---------------------------------------------------------------------
//  LoadROMListFile
//---------------------------------------------------------------------
BOOL CROMListScreen::LoadROMListFile( void )
{
  m_ROMListFull.clear();
  m_ROMStatus.clear();
  m_driverMetadata.clear();

  UINT32 i = 0;
  for( ; i < m_numDrivers; ++i )
    m_ROMStatus.push_back( STATUS_UNKNOWN );

  std::string romListFile = DEFAULT_MAMEOXSYSTEMPATH "\\" ROMLISTFILENAME;
	PRINTMSG(( T_INFO, "  ", romListFile.c_str() ));
//	PRINTMSG(( T_INFO, "Load ROM list: %s", romListFile.c_str() )); Kenny
  osd_file *file = osd_fopen( FILETYPE_MAMEOX_SYSTEM, 0, ROMLISTFILENAME, "r" );
	if( !file )
	{
    PRINTMSG(( T_ERROR, "Failed to open ROM list file %s!", romListFile.c_str() ));
    return FALSE;
  }

    // Grab the entire file at once so we can check its signature
  osd_fseek( file, 0, SEEK_END );
  INT32 fileSize = osd_ftell( file );
  osd_fseek( file, 0, SEEK_SET );
  
  UCHAR *fileData = (UCHAR*)malloc( fileSize );
  if( !fileData )
  {
    osd_fclose( file );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, 
              "Could not malloc space for %s (%lu bytes required)!", 
              romListFile.c_str(), 
              fileSize ));
    return FALSE;
  }

    // Read the entire file into memory
  if( osd_fread( file, fileData, fileSize ) != fileSize )
  {
    free( fileData );
    osd_fclose( file );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed to read file %s!", romListFile.c_str() ));
    return FALSE;
  }
  osd_fclose( file );

    // Check the signature
  if( memcmp( fileData, DRIVERLIST_FILESTAMP, sizeof(DRIVERLIST_FILESTAMP) - 1 ) )
  {
    free( fileData );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Bad file signature!" ));
    return FALSE;
  }

    // Test the data signature
  HANDLE sigHandle = XCalculateSignatureBegin( XCALCSIG_FLAG_SAVE_GAME );
  if( sigHandle == INVALID_HANDLE_VALUE )
  {
    free( fileData );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not calculate driver list signature!" ));
    return FALSE;
  }

  DWORD sigSize = XCalculateSignatureGetSize( XCALCSIG_FLAG_SAVE_GAME );
  void *sigData = calloc( 1, sigSize );
  if( !sigData )
  {
    free( fileData );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not allocate memory for driver list signature!" ));
    return FALSE;
  }

  const BYTE *listData = fileData + ((sizeof(DRIVERLIST_FILESTAMP) - 1) + sigSize);
  DWORD listDataSize = fileSize - ((sizeof(DRIVERLIST_FILESTAMP) - 1) + sigSize);
  if( XCalculateSignatureUpdate( sigHandle, listData, listDataSize ) != ERROR_SUCCESS )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed to calculate data signature!" ));
    return FALSE;
  }
  
    // Grab the signature
  if( XCalculateSignatureEnd( sigHandle, sigData ) != ERROR_SUCCESS )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed getting signature!" ));
    return FALSE;
  }

    // Test the signature
  if( memcmp( (fileData + (sizeof(DRIVERLIST_FILESTAMP)-1)), sigData, sigSize ) )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romListFile.c_str() );
    PRINTMSG(( T_ERROR, "Data signature mismatch!" ));
    return FALSE;
  }
  free( sigData );





    // Define a macro to "read" a block of data and ensure that we're not reading past the end of
    //  the file
  #define READDATA( _data__, _dataSize__, _dataType__ ) \
    if( (DWORD)((listData + (_dataSize__)) - fileData) > fileSize ) \
    { \
      free( fileData ); \
      DeleteFile( romListFile.c_str() ); \
      PRINTMSG(( T_ERROR, "Attempt to read beyond the end of the file!" )); \
      return FALSE; \
    } \
    else \
    { \
    if( !(_data__) && !((_data__) = (_dataType__##*)malloc( (_dataSize__) )) ) \
      { \
        free( fileData ); \
        DeleteFile( romListFile.c_str() ); \
        PRINTMSG(( T_ERROR, "Failed to malloc data array. %lu bytes requested!", (_dataSize__) )); \
        return FALSE; \
      } \
      memcpy( (_data__), listData, (_dataSize__) ); \
      listData += (_dataSize__); \
    }

  #define READDATA_NOMALLOC( _data__, _dataSize__ ) \
    if( (DWORD)((listData + (_dataSize__)) - fileData) > fileSize ) \
    { \
      free( fileData ); \
      DeleteFile( romListFile.c_str() ); \
      PRINTMSG(( T_ERROR, "Attempt to read beyond the end of the file!" )); \
      return FALSE; \
    } \
    else \
    { \
    if( !(_data__) ) \
      { \
        free( fileData ); \
        DeleteFile( romListFile.c_str() ); \
        PRINTMSG(( T_ERROR, "Attempt to read into NULL destination buffer!" )); \
        return FALSE; \
      } \
      memcpy( (_data__), listData, (_dataSize__) ); \
      listData += (_dataSize__); \
    }


    // Read in the number of items
  DWORD numItems;
  READDATA_NOMALLOC( &numItems, sizeof(numItems) );

  for( DWORD i = 0; i < numItems; ++i )
  {
    DWORD idx, status;
      // Read the ROM index
    READDATA_NOMALLOC( &idx, sizeof(idx) );
		m_ROMListFull.push_back( idx );

      // Read the ROM status
    READDATA_NOMALLOC( &status, sizeof(status) );
    m_ROMStatus[idx] = (ROMStatus)status;
  }
  free( fileData );

  if( !LoadROMMetadataFile() )
    PRINTMSG(( T_ERROR, "Failed loading ROM metadata file!" ));


  return TRUE;
}


//---------------------------------------------------------------------
//	SaveROMMetadataFile
//---------------------------------------------------------------------
BOOL CROMListScreen::SaveROMMetadataFile( void )
{
	if (g_rendererOptions.m_fastsave == TRUE)
	{
		return TRUE;
	}
  CStdString romMetadataFile = DEFAULT_MAMEOXSYSTEMPATH "\\" ROMMETADATAFILENAME;

		// Write the indices to the ROM list file
	PRINTMSG(( T_TRACE, "SaveROMMetadataFile" ));
  osd_file *file = osd_fopen( FILETYPE_MAMEOX_SYSTEM, 0, ROMMETADATAFILENAME, "w" );
	if( !file )
	{
		PRINTMSG(( T_ERROR, "Could not create file %s!", romMetadataFile.c_str() ));
		return FALSE;
	}

    // Sign the file
  if( osd_fwrite( file, DRIVERLIST_FILESTAMP, sizeof(DRIVERLIST_FILESTAMP) - 1 ) != sizeof(DRIVERLIST_FILESTAMP) - 1 )
	{
		PRINTMSG(( T_ERROR, "Write failed!" ));
		osd_fclose( file );

			// Delete the file
		DeleteFile( romMetadataFile.c_str() );
		return FALSE;
	}

    // Calculate a signature for the list, so we can validate it when reading
    //  to eliminate corrupt data
  HANDLE sigHandle = XCalculateSignatureBegin( XCALCSIG_FLAG_SAVE_GAME );
  if( sigHandle == INVALID_HANDLE_VALUE )
  {
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not calculate driver list signature!" ));
    return FALSE;
  }

  DWORD sigSize = XCalculateSignatureGetSize( XCALCSIG_FLAG_SAVE_GAME );
  void *sigData = calloc( 1, sigSize );
  if( !sigData )
  {
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not allocate memory for driver list signature!" ));
    return FALSE;
  }

    // Write in a blank signature
  if( osd_fwrite( file, sigData, sigSize ) != sigSize )
  {
    free( sigData );
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed writing blank signature!" ));
    return FALSE;
  }



    // Define a macro to write a block of data and calculate the data signature
  #define METADATA_WRITEDATA( _data__, _dataSize__ ) \
    if( XCalculateSignatureUpdate( sigHandle, (const BYTE *)(_data__), (_dataSize__) ) != ERROR_SUCCESS || \
        osd_fwrite( file, (_data__), (_dataSize__) ) != (_dataSize__) ) \
    { \
      PRINTMSG(( T_ERROR, "Write failed!" )); \
      free( sigData ); \
      osd_fclose( file ); \
      DeleteFile( romMetadataFile.c_str() ); \
      return FALSE; \
    }


    // Write the number of indices
  DWORD numROMs = m_driverMetadata.size();
  METADATA_WRITEDATA( &numROMs, sizeof(numROMs) );

    // Write the indices
	std::vector<MAMEoXDriverMetadata_t>::iterator it = m_driverMetadata.begin();
	for( ; it != m_driverMetadata.end(); ++it )
	{
    DWORD len;

    METADATA_WRITEDATA( &(*it).m_romIndex, sizeof((*it).m_romIndex) );

      // Write the filename
    if( (*it).m_romFileName )
    {
      len = strlen( (*it).m_romFileName ) + 1;
      METADATA_WRITEDATA( &len, sizeof(len) );
      METADATA_WRITEDATA( (*it).m_romFileName, len );
    }
    else
    {
      len = 1;
      METADATA_WRITEDATA( &len, sizeof(len) );
      METADATA_WRITEDATA( "", 1 );
    }

      // Write the favorite status
    METADATA_WRITEDATA( &(*it).m_favoriteStatus, sizeof((*it).m_favoriteStatus) );

      // Write the number of times played
    METADATA_WRITEDATA( &(*it).m_timesPlayed, sizeof((*it).m_timesPlayed) );

      // Write the catver.ini [Category] 
    if( (*it).m_genre )
    {
      len = strlen( (*it).m_genre ) + 1;
      METADATA_WRITEDATA( &len, sizeof(len) );
      METADATA_WRITEDATA( (*it).m_genre, len );
    }
    else
    {
      len = 1;
      METADATA_WRITEDATA( &len, sizeof(len) );
      METADATA_WRITEDATA( "", 1 );
    }

      // Write the catver.ini [VersionAdded] 
    if( (*it).m_versionAdded )
    {
      len = strlen( (*it).m_versionAdded ) + 1;
      METADATA_WRITEDATA( &len, sizeof(len) );
      METADATA_WRITEDATA( (*it).m_versionAdded, len );
    }
    else
    {
      len = 0;
      METADATA_WRITEDATA( &len, sizeof(len) );
    }
	}


    // Grab the signature
  if( XCalculateSignatureEnd( sigHandle, sigData ) != ERROR_SUCCESS )
  {
    free( sigData );
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed getting signature!" ));
    return FALSE;
  }

    // Write in the real signature
  osd_fseek( file, sizeof(DRIVERLIST_FILESTAMP) - 1, SEEK_SET );
  if( osd_fwrite( file, sigData, sigSize ) != sigSize )
  {
    free( sigData );
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed writing signature!" ));
    return FALSE;
  }

  free( sigData );
	osd_fclose( file );
  return TRUE;
}

//---------------------------------------------------------------------
//	LoadROMMetadataFile
//---------------------------------------------------------------------
BOOL CROMListScreen::LoadROMMetadataFile( void )
{
	CStdString romMetadataFile = DEFAULT_MAMEOXSYSTEMPATH "\\" ROMMETADATAFILENAME;
  UINT32 i = 0;
  MAMEoXDriverMetadata_t emptyMetadata;
  memset( &emptyMetadata, 0, sizeof(emptyMetadata) );
   
    // Set the driver metadata to defaults
  m_driverMetadata.clear();
  for( ; i < m_numDrivers; ++i )
  {
    emptyMetadata.m_romFileName = strdup( m_driverInfoList[i].m_romFileName );
    emptyMetadata.m_romIndex = i;
    m_driverMetadata.push_back( emptyMetadata );
  }

	PRINTMSG(( T_INFO, "    ", romMetadataFile.c_str() ));
  osd_file *file = osd_fopen( FILETYPE_MAMEOX_SYSTEM, 0, ROMMETADATAFILENAME, "r" );
	if( !file )
	{
    PRINTMSG(( T_ERROR, "Failed to open ROM metadata file %s!", romMetadataFile.c_str() ));
    return FALSE;
  }

    // Grab the entire file at once so we can check its signature
  osd_fseek( file, 0, SEEK_END );
  INT32 fileSize = osd_ftell( file );
  osd_fseek( file, 0, SEEK_SET );
  
  UCHAR *fileData = (UCHAR*)malloc( fileSize );
  if( !fileData )
  {
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, 
              "Could not malloc space for %s (%lu bytes required)!", 
              romMetadataFile.c_str(), 
              fileSize ));
    return FALSE;
  }

    // Read the entire file into memory
  if( osd_fread( file, fileData, fileSize ) != fileSize )
  {
    free( fileData );
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed to read file %s!", romMetadataFile.c_str() ));
    return FALSE;
  }
  osd_fclose( file );

    // Check the signature
  if( memcmp( fileData, DRIVERLIST_FILESTAMP, sizeof(DRIVERLIST_FILESTAMP) - 1 ) )
  {
    free( fileData );
      // If the signature is not correct, it's quite possible that the file is
      // intact but from an older version. Try updating it to the latest
      // version so we don't lose usage statistics
		return UpdateROMMetadataFile();
  }

    // Test the data signature
  HANDLE sigHandle = XCalculateSignatureBegin( XCALCSIG_FLAG_SAVE_GAME );
  if( sigHandle == INVALID_HANDLE_VALUE )
  {
    free( fileData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not calculate driver list signature!" ));
    return FALSE;
  }

  DWORD sigSize = XCalculateSignatureGetSize( XCALCSIG_FLAG_SAVE_GAME );
  void *sigData = calloc( 1, sigSize );
  if( !sigData )
  {
    free( fileData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not allocate memory for driver list signature!" ));
    return FALSE;
  }

  const BYTE *listData = fileData + ((sizeof(DRIVERLIST_FILESTAMP) - 1) + sigSize);
  DWORD listDataSize = fileSize - ((sizeof(DRIVERLIST_FILESTAMP) - 1) + sigSize);
  if( XCalculateSignatureUpdate( sigHandle, listData, listDataSize ) != ERROR_SUCCESS )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed to calculate data signature!" ));
    return FALSE;
  }
  

    // Grab the signature
  if( XCalculateSignatureEnd( sigHandle, sigData ) != ERROR_SUCCESS )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed getting signature!" ));
    return FALSE;
  }

    // Test the signature
  if( memcmp( (fileData + (sizeof(DRIVERLIST_FILESTAMP)-1)), sigData, sigSize ) )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Data signature mismatch!" ));
    return FALSE;
  }
  free( sigData );


    // Define a macro to "read" a block of data and ensure that we're not reading past the end of
    //  the file
  #define METADATA_READDATA( _data__, _dataSize__, _dataType__ ) \
    if( (DWORD)((listData + (_dataSize__)) - fileData) > fileSize ) \
    { \
      free( fileData ); \
      DeleteFile( romMetadataFile.c_str() ); \
      PRINTMSG(( T_ERROR, "Attempt to read beyond the end of the file!" )); \
      return FALSE; \
    } \
    else \
    { \
    if( !(_data__) && !((_data__) = (_dataType__##*)malloc( (_dataSize__) )) ) \
      { \
        free( fileData ); \
        DeleteFile( romMetadataFile.c_str() ); \
        PRINTMSG(( T_ERROR, "Failed to malloc data array. %lu bytes requested!", (_dataSize__) )); \
        return FALSE; \
      } \
      memcpy( (_data__), listData, (_dataSize__) ); \
      listData += (_dataSize__); \
    }

  #define METADATA_READDATA_NOMALLOC( _data__, _dataSize__ ) \
    if( (DWORD)((listData + (_dataSize__)) - fileData) > fileSize ) \
    { \
      free( fileData ); \
      DeleteFile( romMetadataFile.c_str() ); \
      PRINTMSG(( T_ERROR, "Attempt to read beyond the end of the file!" )); \
      return FALSE; \
    } \
    else \
    { \
    if( !(_data__) ) \
      { \
        free( fileData ); \
        DeleteFile( romMetadataFile.c_str() ); \
        PRINTMSG(( T_ERROR, "Attempt to read into NULL destination buffer!" )); \
        return FALSE; \
      } \
      memcpy( (_data__), listData, (_dataSize__) ); \
      listData += (_dataSize__); \
    }

    // Read in the number of items
  DWORD numItems;
  METADATA_READDATA_NOMALLOC( &numItems, sizeof(numItems) );

  for( DWORD i = 0; i < numItems; ++i )
  {
    DWORD len;
    MAMEoXDriverMetadata_t metadata;
    memset( &metadata, 0, sizeof(metadata) );

      // Read the index
    METADATA_READDATA_NOMALLOC( &metadata.m_romIndex, sizeof(metadata.m_romIndex) );

      // Read the filename
    METADATA_READDATA_NOMALLOC( &len, sizeof(len) );
    METADATA_READDATA( metadata.m_romFileName, len, char );

      // Read the favorite status
    METADATA_READDATA_NOMALLOC( &metadata.m_favoriteStatus, sizeof(metadata.m_favoriteStatus) );

    METADATA_READDATA_NOMALLOC( &metadata.m_timesPlayed, sizeof(metadata.m_timesPlayed) );

      // Read the catver.ini [Category] 
    METADATA_READDATA_NOMALLOC( &len, sizeof(len) );
    if( len )
    {
      METADATA_READDATA( metadata.m_genre, len, char );
    }
    else
      metadata.m_genre = strdup( "Unknown" );

      // Read the catver.ini [VersionAdded] 
    METADATA_READDATA_NOMALLOC( &len, sizeof(len) );
    if( len )
    {
      METADATA_READDATA( metadata.m_versionAdded, len, char );
    }
    else
      metadata.m_versionAdded = strdup( "Unknown" );


      // Add the loaded data to the metadata list
    m_driverMetadata[metadata.m_romIndex] = metadata;
  }
  free( fileData );

  return TRUE;
}

//---------------------------------------------------------------------
//	UpdateROMMetadataFile
//---------------------------------------------------------------------
BOOL CROMListScreen::UpdateROMMetadataFile( void )
{
	CStdString romMetadataFile = DEFAULT_MAMEOXSYSTEMPATH "\\" ROMMETADATAFILENAME;
  UINT32 i = 0;
  MAMEoXDriverMetadata_t emptyMetadata;
  memset( &emptyMetadata, 0, sizeof(emptyMetadata) );
   
    // Set the driver metadata to defaults
  m_driverMetadata.clear();
  for( ; i < m_numDrivers; ++i )
  {
    emptyMetadata.m_romIndex = i;
    m_driverMetadata.push_back( emptyMetadata );
  }

	PRINTMSG(( T_INFO, "    ", romMetadataFile.c_str() ));
	osd_file *file = osd_fopen( FILETYPE_MAMEOX_SYSTEM, 0, ROMMETADATAFILENAME, "r" );
	if( !file )
	{
    PRINTMSG(( T_ERROR, "Failed to open ROM metadata file %s!", romMetadataFile.c_str() ));
    return FALSE;
  }

    // Grab the entire file at once so we can check its signature
  osd_fseek( file, 0, SEEK_END );
  INT32 fileSize = osd_ftell( file );
  osd_fseek( file, 0, SEEK_SET );
  
  UCHAR *fileData = (UCHAR*)malloc( fileSize );
  if( !fileData )
  {
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, 
              "Could not malloc space for %s (%lu bytes required)!", 
              romMetadataFile.c_str(), 
              fileSize ));
    return FALSE;
  }

    // Read the entire file into memory
  if( osd_fread( file, fileData, fileSize ) != fileSize )
  {
    free( fileData );
    osd_fclose( file );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed to read file %s!", romMetadataFile.c_str() ));
    return FALSE;
  }
  osd_fclose( file );

    // Don't waste time on the signature, it's invalid regardless

    // Test the data signature
  HANDLE sigHandle = XCalculateSignatureBegin( XCALCSIG_FLAG_SAVE_GAME );
  if( sigHandle == INVALID_HANDLE_VALUE )
  {
    free( fileData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not calculate driver list signature!" ));
    return FALSE;
  }

  DWORD sigSize = XCalculateSignatureGetSize( XCALCSIG_FLAG_SAVE_GAME );
  void *sigData = calloc( 1, sigSize );
  if( !sigData )
  {
    free( fileData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Could not allocate memory for driver list signature!" ));
    return FALSE;
  }

  const BYTE *listData = fileData + ((sizeof(DRIVERLIST_FILESTAMP) - 1) + sigSize);
  DWORD listDataSize = fileSize - ((sizeof(DRIVERLIST_FILESTAMP) - 1) + sigSize);
  if( XCalculateSignatureUpdate( sigHandle, listData, listDataSize ) != ERROR_SUCCESS )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed to calculate data signature!" ));
    return FALSE;
  }
  


    // Grab the signature
  if( XCalculateSignatureEnd( sigHandle, sigData ) != ERROR_SUCCESS )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Failed getting signature!" ));
    return FALSE;
  }

    // Test the signature
  if( memcmp( (fileData + (sizeof(DRIVERLIST_FILESTAMP)-1)), sigData, sigSize ) )
  {
    free( fileData );
    free( sigData );
		DeleteFile( romMetadataFile.c_str() );
    PRINTMSG(( T_ERROR, "Data signature mismatch!" ));
    return FALSE;
  }
  free( sigData );


    // Define a macro to "read" a block of data and ensure that we're not reading past the end of
    //  the file
  #define METADATA_READDATA( _data__, _dataSize__, _dataType__ ) \
    if( (DWORD)((listData + (_dataSize__)) - fileData) > fileSize ) \
    { \
      free( fileData ); \
      DeleteFile( romMetadataFile.c_str() ); \
      PRINTMSG(( T_ERROR, "Attempt to read beyond the end of the file!" )); \
      return FALSE; \
    } \
    else \
    { \
    if( !(_data__) && !((_data__) = (_dataType__##*)malloc( (_dataSize__) )) ) \
      { \
        free( fileData ); \
        DeleteFile( romMetadataFile.c_str() ); \
        PRINTMSG(( T_ERROR, "Failed to malloc data array. %lu bytes requested!", (_dataSize__) )); \
        return FALSE; \
      } \
      memcpy( (_data__), listData, (_dataSize__) ); \
      listData += (_dataSize__); \
    }

  #define METADATA_READDATA_NOMALLOC( _data__, _dataSize__ ) \
    if( (DWORD)((listData + (_dataSize__)) - fileData) > fileSize ) \
    { \
      free( fileData ); \
      DeleteFile( romMetadataFile.c_str() ); \
      PRINTMSG(( T_ERROR, "Attempt to read beyond the end of the file!" )); \
      return FALSE; \
    } \
    else \
    { \
    if( !(_data__) ) \
      { \
        free( fileData ); \
        DeleteFile( romMetadataFile.c_str() ); \
        PRINTMSG(( T_ERROR, "Attempt to read into NULL destination buffer!" )); \
        return FALSE; \
      } \
      memcpy( (_data__), listData, (_dataSize__) ); \
      listData += (_dataSize__); \
    }

    // Read in the number of items
  DWORD numItems;
  METADATA_READDATA_NOMALLOC( &numItems, sizeof(numItems) );

  for( DWORD i = 0; i < numItems; ++i )
  {
    DWORD len;
    MAMEoXDriverMetadata_t metadata;

      // Read the index
    METADATA_READDATA_NOMALLOC( &metadata.m_romIndex, sizeof(metadata.m_romIndex) );

      // Read the filename
    METADATA_READDATA_NOMALLOC( &len, sizeof(len) );
    METADATA_READDATA( metadata.m_romFileName, len, char );

      // Read the favorite status
    METADATA_READDATA_NOMALLOC( &metadata.m_favoriteStatus, sizeof(metadata.m_favoriteStatus) );

    METADATA_READDATA_NOMALLOC( &metadata.m_timesPlayed, sizeof(metadata.m_timesPlayed) );

      // Read the catver.ini [Category] 
    METADATA_READDATA_NOMALLOC( &len, sizeof(len) );
    METADATA_READDATA( metadata.m_genre, len, char );

      // Read the catver.ini [VersionAdded] 
    METADATA_READDATA_NOMALLOC( &len, sizeof(len) );
    METADATA_READDATA( metadata.m_versionAdded, len, char );

    DrawProgressbarMessage( m_displayDevice, 
                            "Please Wait...", 
                            metadata.m_romFileName, 
                            i, 
                            0 );

      // Find the index for this ROM
    UINT32 index;
      // Go through the m_driverInfoList and find the entry matching that read from the XML file
    for( index = 0; index < m_numDrivers && stricmp( m_driverInfoList[index].m_romFileName, metadata.m_romFileName ); ++index )
      ;

    m_driverMetadata[i] = metadata;
  }
  free( fileData );

  return TRUE;
}

//---------------------------------------------------------------------
//	Play Random Game // Ken
//---------------------------------------------------------------------

BOOL CROMListScreen::RandomPlayed( void )
 {
	 
	 if (m_options.m_hideFiltered == false && g_romListOptions.m_showclassic == TRUE)
	 RandomFav();
	 else
	Random();
	return TRUE;
	}

//---------------------------------------------------------------------
//	Play Random Fav // Ken
//---------------------------------------------------------------------

BOOL CROMListScreen::RandomFav( void )
 {
	 m_options.m_hideFiltered = TRUE;
	UpdateSortedList();
    UpdateSortedList();
	m_pageOffset = 0;
	m_cursorPosition = 0;
	m_pageOffset = rand() % (m_currentSortedList.size() );
    UpdateSortedList();
    UpdateSortedList();
	m_options.m_hideFiltered = false;
	UpdateSortedList();
    UpdateSortedList();
	if ( g_romListOptions.m_showhot == false)
	{

		if (m_ROMStatus[GetCurrentGameIndex()] == 3)
			{
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = driverData.m_romFileName[0] ;
	  bufa[1] = driverData.m_romFileName[1] ;
	  bufa[2] = driverData.m_romFileName[2] ;
	  bufa[3] = driverData.m_romFileName[3] ;


	  if ( bufa[0] == 's' && bufa[1] == 'f' && bufa[2] == 'i' && bufa[3] == 'i')
	  {
		   XLaunchNewImage("D:\\StreetFighter3.xbe", NULL);
	  }
	  	  if ( bufa[0] == 'K' && bufa[1] == 'I' && bufa[2] == '1')
	  {
		   XLaunchNewImage("D:\\KI1.xbe", NULL);
	  }
	  	  	  if ( bufa[0] == 'K' && bufa[1] == 'I' && bufa[2] == '2')
	  {
		   XLaunchNewImage("D:\\KI2.xbe", NULL);
	  }
	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "game=%s\n", driverData.m_romFileName);
		fclose(f);
			  			  	  if ( bufa[0] == 'h' && bufa[1] == 's' && bufa[2] == 'f' && bufa[3] == '2')
	 {
		   XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);   // Run hyper street fighter 2 aniversery edition
	  }
	 	 			  	  if ( bufa[0] == 'k' && bufa[1] == 'f' && bufa[2] == '1' && bufa[3] == '0')
	 {
		   XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);   // Run KOF 10th aniversery edition
	  }
		XLaunchNewImage("D:\\FinalBurn.xbe", NULL);
	  }

			if ((m_ROMStatus[GetCurrentGameIndex()] == 1) && g_romListOptions.m_finalburncore == 0)
			{
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
				MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
		  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "game=%s\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);
	  }


		MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = driverData.m_romFileName[0] ;
	  bufa[1] = driverData.m_romFileName[1] ;
	  bufa[2] = driverData.m_romFileName[2] ;
	  bufa[3] = driverData.m_romFileName[3] ;

 if ( bufa[0] == 'N' && bufa[1] == '6' && bufa[2] == '4') // N64
	 {
			//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\RomsN64\\%s.zip", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\N64core.xbe", NULL);
	  }

	  if ( bufa[0] == 'S' && bufa[1] == 'N' && bufa[2] == 'E' && bufa[3] == 'S') // SNES
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\SNEScore.xbe", NULL);
	  }

	    if ( bufa[0] == 'X' && bufa[1] == 'B' && bufa[2] == 'O' && bufa[3] == 'X') // XBOX
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );
				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];      	 
	CStdString filename;
	  	filename.Format( "D:\\%s.xbe", driverData.m_romFileName );		
		XLaunchNewImage( filename.c_str() , NULL);
	  }

	  if ( bufa[0] == 'C' && bufa[1] == '6' && bufa[2] == '4' && bufa[3] == '_') // C64
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\C64.xbe", NULL);
	  }

	   if ( bufa[0] == 'P' && bufa[1] == 'S' && bufa[2] == 'X' && bufa[3] == '_') // Playstation
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;
		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.bin", driverData.m_romFileName);
		fclose(f);

		FILE *g;
		g = fopen("D:\\game2.txt", "w+");
		fprintf(g, "D:\\roms\\%s.iso", driverData.m_romFileName);
		fclose(g);

		FILE *h;
		h = fopen("D:\\game3.txt", "w+");
		fprintf(h, "D:\\roms\\%s.img", driverData.m_romFileName);
		fclose(h);

		FILE *j;
		j = fopen("D:\\game4.txt", "w+");
		fprintf(j, "D:\\roms\\%s.tao", driverData.m_romFileName);
		fclose(j);

		XLaunchNewImage("D:\\PSXcore.xbe", NULL);
	  }

	  if ( bufa[0] == 'M' && bufa[1] == 'D' && bufa[2] == 'R' && bufa[3] == 'I') // MEGADRIVE
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\MEGADRIVEcore.xbe", NULL);
	  }


	  if ( bufa[0] == 'P' && bufa[1] == 'C' && bufa[2] == 'E' && bufa[3] == '_') // PCE
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\PCEcore.xbe", NULL);
	  }

	   if ( bufa[0] == 'P' && bufa[1] == 'C' && bufa[2] == 'D' && bufa[3] == '_') // PCE CD
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s\\MP3.cue", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\PCEcore.xbe", NULL);
	  }
	  if ( bufa[0] == 'M' && bufa[1] == 'I' && bufa[2] == '_') // Midway Core
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	if (bufa[3] == '1')
	{
		XLaunchNewImage("D:\\MI_1.xbe", NULL);
	}
	if (bufa[3] == '2')
	{
		XLaunchNewImage("D:\\MI_2.xbe", NULL);
	}
		if (bufa[3] == '3')
	{
		XLaunchNewImage("D:\\MI_3.xbe", NULL);
	}
		if (bufa[3] == '4')
	{
		XLaunchNewImage("D:\\MI_4.xbe", NULL);
	}
		if (bufa[3] == '5')
	{
		XLaunchNewImage("D:\\MI_5.xbe", NULL);
	}
			if (bufa[3] == '6')
	{
		XLaunchNewImage("D:\\Doom2.xbe", NULL);
	}
				if (bufa[3] == '7')
	{
		XLaunchNewImage("D:\\DoomFinal.xbe", NULL);
	}
				if (bufa[3] == '8')
	{
		XLaunchNewImage("D:\\DoomFinal2.xbe", NULL);
	}
	  }

	  	  if ( bufa[0] == 'N' && bufa[1] == 'E' && bufa[2] == 'S' && bufa[3] == '_') // NES
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\NEScore.xbe", NULL);
	  }

	  	  if ( bufa[0] == 'L' && bufa[1] == 'Y' && bufa[2] == 'N' && bufa[3] == 'X') // LYNX
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\LYNXcore.xbe", NULL);
	  }

	  	  if (( bufa[0] == 'S' && bufa[1] == 'M' && bufa[2] == 'S' && bufa[3] == '_') || ( bufa[0] == 'G' && bufa[1] == 'G' && bufa[2] == '_') || ( bufa[0] == 'S' && bufa[1] == 'G' && bufa[2] == '_')) // Master System and Gamegear
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\SMScore.xbe", NULL);
	  }

	  	  if (( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == 'A' && bufa[3] == '_') || ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == '_') || ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == 'C' && bufa[3] == '_')) // Gameboys
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\GBAcore.xbe", NULL);
	  }



	if (g_romListOptions.m_rotate == TRUE)
{
	 MAMEoXDriverMetadata_t  &metadata   = m_driverMetadata[GetCurrentGameIndex()];
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = metadata.m_genre[0] ;
	  bufa[1] = metadata.m_genre[1] ;
	  bufa[2] = metadata.m_genre[9] ;
	  bufa[3] = metadata.m_genre[10] ;

	  if (( bufa[0] == 'S' && bufa[1] == 'h' && bufa[2] == 'T' && bufa[3] == 'o') || g_romListOptions.m_onlyrotateshooters == false)
	  {
		if (driverData.m_screenOrientation & ORIENTATION_SWAP_XY)// Ken
			{
				g_rendererOptions.m_screenRotation = SR_90; 
			}
	  }
	}

if (g_rendererOptions.m_rotationkeys == TRUE )// Ken2
			{
					MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
				g_rendererOptions.m_screenRotation = SR_270; 
				if (driverData.m_screenOrientation & ORIENTATION_SWAP_XY)// Ken
					{
						g_rendererOptions.m_screenRotation = SR_180; 
					}
			}			
		

	
	g_soundEnabled = TRUE;

		if (m_ROMStatus[GetCurrentGameIndex()] == 2 && ( g_romListOptions.m_autosound == TRUE ))
		{
			g_soundEnabled = FALSE;
		}
				if (m_ROMStatus[GetCurrentGameIndex()] != 2 && ( g_romListOptions.m_autosound == TRUE ))
		{
			g_soundEnabled = TRUE;
		}
				if (g_romListOptions.m_soundlockout == TRUE && ( g_romListOptions.m_autosound == FALSE ))
		{
			g_soundEnabled = FALSE;
		}

			// Run the selected ROM
    if( GetCurrentGameIndex() != INVALID_ROM_INDEX  )
    {
      if( !m_gameSelected )
      {
        m_gameSelected = TRUE;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				SaveROMMetadataFile();
				UpdateSortedList();
				UpdateSortedList();
      }
	 }
	}
	return TRUE;
  }




//---------------------------------------------------------------------
//	Play Random Game // Ken
//---------------------------------------------------------------------

BOOL CROMListScreen::Random( void )
  {
	m_pageOffset = 0;
	m_cursorPosition = 0;
	m_pageOffset = rand() % (m_currentSortedList.size() );
    UpdateSortedList();
    UpdateSortedList();
	// gp.WaitForNoButton();
	if ( g_romListOptions.m_showhot == false)
	{
		if (m_ROMStatus[GetCurrentGameIndex()] == 3)
			{
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = driverData.m_romFileName[0] ;
	  bufa[1] = driverData.m_romFileName[1] ;
	  bufa[2] = driverData.m_romFileName[2] ;
	  bufa[3] = driverData.m_romFileName[3] ;


	  if ( bufa[0] == 's' && bufa[1] == 'f' && bufa[2] == 'i' && bufa[3] == 'i')
	  {
		   XLaunchNewImage("D:\\StreetFighter3.xbe", NULL);
	  }
	  	  if ( bufa[0] == 'K' && bufa[1] == 'I' && bufa[2] == '1')
	  {
		   XLaunchNewImage("D:\\KI1.xbe", NULL);
	  }
	  	  	  if ( bufa[0] == 'K' && bufa[1] == 'I' && bufa[2] == '2')
	  {
		   XLaunchNewImage("D:\\KI2.xbe", NULL);
	  }
	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "game=%s\n", driverData.m_romFileName);
		fclose(f);
			  	  if ( bufa[0] == 'h' && bufa[1] == 's' && bufa[2] == 'f' && bufa[3] == '2')
	 {
		   XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);   // Run hyper street fighter 2 aniversery edition
	  }
	 			  	  if ( bufa[0] == 'k' && bufa[1] == 'f' && bufa[2] == '1' && bufa[3] == '0')
	 {
		   XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);   // Run KOF 10th aniversery edition
	  }
		XLaunchNewImage("D:\\FinalBurn.xbe", NULL);
	  }

			if ((m_ROMStatus[GetCurrentGameIndex()] == 1) && g_romListOptions.m_finalburncore == 0)
			{
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
				MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
		  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "game=%s\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);
	  }

	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = driverData.m_romFileName[0] ;
	  bufa[1] = driverData.m_romFileName[1] ;
	  bufa[2] = driverData.m_romFileName[2] ;
	  bufa[3] = driverData.m_romFileName[3] ;

  if ( bufa[0] == 'N' && bufa[1] == '6' && bufa[2] == '4') // N64
	 {
			//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\RomsN64\\%s.zip", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\N64core.xbe", NULL);
	  }

	  if ( bufa[0] == 'S' && bufa[1] == 'N' && bufa[2] == 'E' && bufa[3] == 'S') // SNES
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\SNEScore.xbe", NULL);
	  }

	    if ( bufa[0] == 'X' && bufa[1] == 'B' && bufa[2] == 'O' && bufa[3] == 'X') // XBOX
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );
				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];      	 
	CStdString filename;
	  filename.Format( "D:\\%s.xbe", driverData.m_romFileName );		
		XLaunchNewImage( filename.c_str() , NULL);
	  }

	   if ( bufa[0] == 'C' && bufa[1] == '6' && bufa[2] == '4' && bufa[3] == '_') // C64
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\C64.xbe", NULL);
	  }
	   if ( bufa[0] == 'P' && bufa[1] == 'S' && bufa[2] == 'X' && bufa[3] == '_') // Playstation
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;
		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.bin", driverData.m_romFileName);
		fclose(f);

		FILE *g;
		g = fopen("D:\\game2.txt", "w+");
		fprintf(g, "D:\\roms\\%s.iso", driverData.m_romFileName);
		fclose(g);

		FILE *h;
		h = fopen("D:\\game3.txt", "w+");
		fprintf(h, "D:\\roms\\%s.img", driverData.m_romFileName);
		fclose(h);

		FILE *j;
		j = fopen("D:\\game4.txt", "w+");
		fprintf(j, "D:\\roms\\%s.tao", driverData.m_romFileName);
		fclose(j);

		XLaunchNewImage("D:\\PSXcore.xbe", NULL);
	  }

	  if ( bufa[0] == 'M' && bufa[1] == 'D' && bufa[2] == 'R' && bufa[3] == 'I') // Megadrive
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\MEGADRIVEcore.xbe", NULL);
	  }

	  	  if ( bufa[0] == 'P' && bufa[1] == 'C' && bufa[2] == 'E' && bufa[3] == '_') // PCE
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\PCEcore.xbe", NULL);
	  }

	   if ( bufa[0] == 'P' && bufa[1] == 'C' && bufa[2] == 'D' && bufa[3] == '_') // PCE CD
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s\\MP3.cue", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\PCEcore.xbe", NULL);
	  }
	   if ( bufa[0] == 'M' && bufa[1] == 'I' && bufa[2] == '_') // Midway Core
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	if (bufa[3] == '1')
	{
		XLaunchNewImage("D:\\MI_1.xbe", NULL);
	}
	if (bufa[3] == '2')
	{
		XLaunchNewImage("D:\\MI_2.xbe", NULL);
	}
		if (bufa[3] == '3')
	{
		XLaunchNewImage("D:\\MI_3.xbe", NULL);
	}
		if (bufa[3] == '4')
	{
		XLaunchNewImage("D:\\MI_4.xbe", NULL);
	}
		if (bufa[3] == '5')
	{
		XLaunchNewImage("D:\\MI_5.xbe", NULL);
	}
			if (bufa[3] == '6')
	{
		XLaunchNewImage("D:\\Doom2.xbe", NULL);
	}
				if (bufa[3] == '7')
	{
		XLaunchNewImage("D:\\DoomFinal.xbe", NULL);
	}
				if (bufa[3] == '8')
	{
		XLaunchNewImage("D:\\DoomFinal2.xbe", NULL);
	}
	  }

	  	  if ( bufa[0] == 'N' && bufa[1] == 'E' && bufa[2] == 'S' && bufa[3] == '_') // NES
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\NEScore.xbe", NULL);
	  }

	  	  if ( bufa[0] == 'L' && bufa[1] == 'Y' && bufa[2] == 'N' && bufa[3] == 'X') // LYNX
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\LYNXcore.xbe", NULL);
	  }

	  	  if (( bufa[0] == 'S' && bufa[1] == 'M' && bufa[2] == 'S' && bufa[3] == '_') || ( bufa[0] == 'G' && bufa[1] == 'G' && bufa[2] == '_') || ( bufa[0] == 'S' && bufa[1] == 'G' && bufa[2] == '_')) // Master System and Gamegear
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\SMScore.xbe", NULL);
	  }

	  	  if (( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == 'A' && bufa[3] == '_') || ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == '_') || ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == 'C' && bufa[3] == '_')) // Gameboys
	  {
				//++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\GBAcore.xbe", NULL);
	  }

	  


	if (g_romListOptions.m_rotate == TRUE)
{
	 MAMEoXDriverMetadata_t  &metadata   = m_driverMetadata[GetCurrentGameIndex()];
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = metadata.m_genre[0] ;
	  bufa[1] = metadata.m_genre[1] ;
	  bufa[2] = metadata.m_genre[9] ;
	  bufa[3] = metadata.m_genre[10] ;

	  if (( bufa[0] == 'S' && bufa[1] == 'h' && bufa[2] == 'T' && bufa[3] == 'o') || g_romListOptions.m_onlyrotateshooters == false)
	  {
		if (driverData.m_screenOrientation & ORIENTATION_SWAP_XY)// Ken
			{
				g_rendererOptions.m_screenRotation = SR_90; 
			}
	  }
	}

if (g_rendererOptions.m_rotationkeys == TRUE )// Ken2
			{
					MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
				g_rendererOptions.m_screenRotation = SR_270; 
				if (driverData.m_screenOrientation & ORIENTATION_SWAP_XY)// Ken
					{
						g_rendererOptions.m_screenRotation = SR_180; 
					}
			}			
		

	
	g_soundEnabled = TRUE;

		if (m_ROMStatus[GetCurrentGameIndex()] == 2 && ( g_romListOptions.m_autosound == TRUE ))
		{
			g_soundEnabled = FALSE;
		}
				if (m_ROMStatus[GetCurrentGameIndex()] != 2 && ( g_romListOptions.m_autosound == TRUE ))
		{
			g_soundEnabled = TRUE;
		}
				if (g_romListOptions.m_soundlockout == TRUE && ( g_romListOptions.m_autosound == FALSE ))
		{
			g_soundEnabled = FALSE;
		}

			// Run the selected ROM
    if( GetCurrentGameIndex() != INVALID_ROM_INDEX  )
    {
      if( !m_gameSelected )
      {
        m_gameSelected = TRUE;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				SaveROMMetadataFile();
				UpdateSortedList();
				UpdateSortedList();
      }
	 }
	}
	return TRUE;
  }


//---------------------------------------------------------------------
//	Reset Times Played // Ken
//---------------------------------------------------------------------

BOOL CROMListScreen::RemoveTimesPlayed( void )
{
				m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed = 0;
				SaveROMMetadataFile();
					UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();
				return TRUE;
}

//---------------------------------------------------------------------
//	Add 10 Times Played // Ken
//---------------------------------------------------------------------

BOOL CROMListScreen::AddTimesPlayed( void )
{
				m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed = m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed + 10;;
				SaveROMMetadataFile();
					UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();
				return TRUE;
}

//---------------------------------------------------------------------
//	Add 100 Times Played // Ken
//---------------------------------------------------------------------

BOOL CROMListScreen::MassTimesPlayed( void )
{
				m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed = m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed + 100;;
				SaveROMMetadataFile();
					UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();
				return TRUE;
}

//---------------------------------------------------------------------
//	Refresh Screen // Ken
//---------------------------------------------------------------------

BOOL CROMListScreen::RefreshScreen( void )
{
	UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();
	return TRUE;
}

//---------------------------------------------------------------------
//	Refresh Picture // Ken
//---------------------------------------------------------------------

BOOL CROMListScreen::RefreshPicture( void )
{
LoadScreenshotFile( 0 );
	UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();
	return TRUE;
}



//---------------------------------------------------------------------
//	ImportCatverINI
//---------------------------------------------------------------------
BOOL CROMListScreen::ImportCatverINI( void )
{
  CStdString iniFileName = g_FileIOConfig.m_generalPath;
  iniFileName += "\\catver.ini";

  DrawProgressbarMessage( m_displayDevice, 
                          "Please Wait...", 
                          "", 
                          0xFFFFFFFF, 
                          0 );


    // Make sure there's a file to parse
  osd_file *file = osd_fopen( FILETYPE_HISTORY, 0, "catver.ini", "r" );
  if( !file )
    return FALSE;
  osd_fclose( file );

  CSystem_IniFile iniFile( iniFileName );

  std::vector<MAMEoXDriverMetadata_t>::iterator it = m_driverMetadata.begin();
  UINT32 i = 0;
  for( ; it != m_driverMetadata.end(); ++it, ++i )
  {
    if( (*it).m_romFileName )
    {
      CStdString tempStr;
      

        // Only draw every 8th item
      if( !(i & 0x07) ) 
        DrawProgressbarMessage( m_displayDevice, 
                                "Please Wait...", 
                                (*it).m_romFileName, 
                                i, 
                                m_driverMetadata.size() );

        // Grab the category
      tempStr = iniFile.GetProfileString( "Category", (*it).m_romFileName, "Added Game" );
	 //    tempStr = iniFile.GetProfileString( "Category", (*it).m_romFileName, "[Unknown]" );
      if( (*it).m_genre )
        free( (*it).m_genre );
      (*it).m_genre = strdup( tempStr.c_str() );

        // Grab the version added
      tempStr = iniFile.GetProfileString( "VerAdded", (*it).m_romFileName, "[Unknown]" );
      if( (*it).m_versionAdded )
        free( (*it).m_versionAdded );
      (*it).m_versionAdded = strdup( tempStr.c_str() );
    }
  }

  return TRUE;
}

//---------------------------------------------------------------------
//	RefreshROMStatus
//---------------------------------------------------------------------
BOOL CROMListScreen::RefreshROMStatus( void )
{
  DrawProgressbarMessage( m_displayDevice, 
                          "Please Wait...", 
                          "", 
                          0xFFFFFFFF, 
                          0 );
  if( !LoadROMStatusFile() )
  {
    PRINTMSG(( T_ERROR, "Failed to load the ROM status file" ));
    return FALSE;
  }

  DrawProgressbarMessage( m_displayDevice, 
                          "Please Wait...", 
                          "", 
                          0xFFFFFFFF, 
                          0 );


  if( !SaveROMListFile() )
  {
    PRINTMSG(( T_ERROR, "Failed to save the ROM list file" ));
    return FALSE;
  }

  return TRUE;
}

//---------------------------------------------------------------------
//	LoadROMStatusFile
//---------------------------------------------------------------------
BOOL CROMListScreen::LoadROMStatusFile( void )
{
  m_ROMStatus.clear();

  UINT32 i = 0;
  for( ; i < m_numDrivers; ++i )
    m_ROMStatus.push_back( STATUS_UNKNOWN );

    // Open the ROMStatus.XML file (in the General directory)
  osd_file *file = osd_fopen( FILETYPE_HISTORY, 0, ROMSTATUSFILENAME, "r" );
  if( !file )
  {
    PRINTMSG(( T_ERROR, "Failed to open rom status file: %s", ROMSTATUSFILENAME ));
    return FALSE;
  }

  char buffer[2] = {0};
  UINT32 entryNumber = 0; // Throw away index number for DrawZipData usage
  CStdString tagName = "";
  CStdString closingTagName = "";
  CStdString tagData = "";
  CStdString romName = "";
  ROMStatus  romStatus = STATUS_UNKNOWN;

  while( osd_fread( file, buffer, 1 ) )
  {
    /*
      <Rom name="005" version="?">
        <Status>Working</Status> 
        <Statusnumber>1</Statusnumber> 
      </Rom>
    */
    
      // Go through the XML file, reading each <ROM> entry into the temp vars
    if( buffer[0] == '<' )
    {
        // Read the entire tag
      if( !Helper_ReadXMLTag( file, &tagName ) )
        break;

      if( tagName == "</rom>" )
      {
          // Just finished reading a ROM entry
          // Go through the m_driverInfoList and find the entry matching that read from the XML file
        for( i = 0; i < m_numDrivers && stricmp( m_driverInfoList[i].m_romFileName, romName.c_str() ); ++i )
          ;

          // Don't redraw for every entry, as that will slow the parsing down drastically
        if( !(entryNumber & 0x03) )
        {
          DrawProgressbarMessage( m_displayDevice, 
                                  "Please Wait...", 
                                  romName.c_str(), 
                                  entryNumber++, 
                                  0 );
        }

          // Set m_ROMStatus at the same index
        if( i != m_numDrivers )
          m_ROMStatus[i] = romStatus;
        else
          PRINTMSG(( T_INFO, "Unknown driver %s in status XML file!", "" ));

        romName = "";
        romStatus = STATUS_UNKNOWN;
      }
      else if( tagName.substr( 0, 2 ) == "<?" || 
          tagName.substr( 0, 2 ) == "<!" || 
          tagName.substr( 0, 2 ) == "</" ||
          tagName == "<roms>" )
      {
          // Just ignore it
      }
      else if( tagName.substr( 0, 5 ) == "<rom " )
      {
          // Don't parse the whole tag, as we want the subfields separate
        romName = tagName.substr( 11 );
        i = romName.find( '"' );
        if( i != romName.npos )
          romName = romName.substr( 0, i );
      }
      else
      {
        tagData = "";

findEndTag:
          // Read until we find the end of this tag
        while( osd_fread( file, buffer, 1 ) && buffer[0] != '<' )
          tagData += buffer;

          // Read the tag
        if( !Helper_ReadXMLTag( file, &closingTagName ) )
          break;

        if( closingTagName.substr( 0, 2 ) != "</" || closingTagName.substr( 2 ) != tagName.substr( 1 ) )
        {
            // We've found a tag, but it's not the one we're looking for. Add it to the data and continue
            // searching
          tagData += closingTagName;
          goto findEndTag;
        }


          // Handle the basic tags
        if( tagName == "<statusnumber>" )
        {
            // Parse out the status ID
          UINT32 statusNum;
          sscanf( tagData.c_str(), "%lu", &statusNum );
          if( statusNum < STATUS_MAX )
            romStatus = (ROMStatus)statusNum;
        }
      }
    }
  }

  osd_fclose( file );

  return TRUE;
}

//---------------------------------------------------------------------
//	MoveCursor
//---------------------------------------------------------------------
void CROMListScreen::MoveCursor( CInputManager &gp, BOOL useSpeedBanding )
{

			if (g_rendererOptions.m_rotationkeys == false)
		{
			g_rendererOptions.m_screenRotation = SR_0;
		}
			if ((g_rendererOptions.m_rotationkeys == TRUE) && (g_rendererOptions.m_OnSide == false))
		{
			g_rendererOptions.m_screenRotation = SR_180;
		}
			if ((g_rendererOptions.m_rotationkeys == TRUE) && (g_rendererOptions.m_OnSide == TRUE))
		{
			g_rendererOptions.m_screenRotation = SR_270;
		}
   	// Handle user input
  // if(( gp.IsButtonPressed( GP_A ) || gp.IsKeyPressed( VK_RETURN )  ) && (m_ROMListFull.size() <= 1130))   // Ken
	    if(( gp.IsButtonPressed( GP_A ) || gp.IsKeyPressed( VK_RETURN )  ))   
	{
			if (g_romListOptions.m_addto == TRUE && (m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed >= 5))
			{
				     DWORD currentGameIdx = GetCurrentGameIndex();
					 if( currentGameIdx != INVALID_ROM_INDEX )
							{
								MAMEoXDriverMetadata_t  &metadata = m_driverMetadata[currentGameIdx];
								metadata.m_favoriteStatus = FS_STRONGLIKE;
							}
			}

			if (m_ROMStatus[GetCurrentGameIndex()] == 3)
			{
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = driverData.m_romFileName[0] ;
	  bufa[1] = driverData.m_romFileName[1] ;
	  bufa[2] = driverData.m_romFileName[2] ;
	  bufa[3] = driverData.m_romFileName[3] ;


	  if ( bufa[0] == 's' && bufa[1] == 'f' && bufa[2] == 'i' && bufa[3] == 'i')
	  {
		   XLaunchNewImage("D:\\StreetFighter3.xbe", NULL);
	  }
	  	  if ( bufa[0] == 'K' && bufa[1] == 'I' && bufa[2] == '1')
	  {
		   XLaunchNewImage("D:\\KI1.xbe", NULL);
	  }
	  	  	  if ( bufa[0] == 'K' && bufa[1] == 'I' && bufa[2] == '2')
	  {
		   XLaunchNewImage("D:\\KI2.xbe", NULL);
	  }
	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "game=%s\n", driverData.m_romFileName);
		fclose(f);
			  	  if ( bufa[0] == 'h' && bufa[1] == 's' && bufa[2] == 'f' && bufa[3] == '2')
	 {
		   XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);   // Run hyper street fighter 2 aniversery edition
	  }
	 	 			  	  if ( bufa[0] == 'k' && bufa[1] == 'f' && bufa[2] == '1' && bufa[3] == '0')
	 {
		   XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);   // Run KOF 10th aniversery edition
	  }
		XLaunchNewImage("D:\\FinalBurn.xbe", NULL);
	  }

			if ((m_ROMStatus[GetCurrentGameIndex()] == 1) && g_romListOptions.m_finalburncore == 0)
			{
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
				MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
		  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "game=%s\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\NeoGeoCPS2.xbe", NULL);
	  }

		MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = driverData.m_romFileName[0] ;
	  bufa[1] = driverData.m_romFileName[1] ;
	  bufa[2] = driverData.m_romFileName[2] ;
	  bufa[3] = driverData.m_romFileName[3] ;

 if ( bufa[0] == 'N' && bufa[1] == '6' && bufa[2] == '4' && bufa[3] == '_') // N64
	  {
			++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\RomsN64\\%s.zip", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\N64core.xbe", NULL);
	  }

	  if ( bufa[0] == 'S' && bufa[1] == 'N' && bufa[2] == 'E' && bufa[3] == 'S') // SNES
	  {
			++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\SNEScore.xbe", NULL);
	  }

	    if ( bufa[0] == 'X' && bufa[1] == 'B' && bufa[2] == 'O' && bufa[3] == 'X') // XBOX
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );
				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];      	 
	CStdString filename;
	  	filename.Format( "D:\\%s.xbe", driverData.m_romFileName );		
		XLaunchNewImage( filename.c_str() , NULL);
	  }

	   if ( bufa[0] == 'C' && bufa[1] == '6' && bufa[2] == '4' && bufa[3] == '_') // C64
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\C64.xbe", NULL);
	  }
	  if ( bufa[0] == 'P' && bufa[1] == 'S' && bufa[2] == 'X' && bufa[3] == '_') // Playstation
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;
		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.bin", driverData.m_romFileName);
		fclose(f);

		FILE *g;
		g = fopen("D:\\game2.txt", "w+");
		fprintf(g, "D:\\roms\\%s.iso", driverData.m_romFileName);
		fclose(g);

		FILE *h;
		h = fopen("D:\\game3.txt", "w+");
		fprintf(h, "D:\\roms\\%s.img", driverData.m_romFileName);
		fclose(h);

		FILE *j;
		j = fopen("D:\\game4.txt", "w+");
		fprintf(j, "D:\\roms\\%s.tao", driverData.m_romFileName);
		fclose(j);

		XLaunchNewImage("D:\\PSXcore.xbe", NULL);
	  }

      	  if ( bufa[0] == 'M' && bufa[1] == 'D' && bufa[2] == 'R' && bufa[3] == 'I') // MEGADRIVE
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\MEGADRIVEcore.xbe", NULL);
	  }

	  	  if ( bufa[0] == 'P' && bufa[1] == 'C' && bufa[2] == 'E' && bufa[3] == '_') // PCE
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\PCEcore.xbe", NULL);
	  }

	   if ( bufa[0] == 'P' && bufa[1] == 'C' && bufa[2] == 'D' && bufa[3] == '_') // PCE CD
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s\\MP3.cue", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\PCEcore.xbe", NULL);
	  }

	   if ( bufa[0] == 'M' && bufa[1] == 'I' && bufa[2] == '_') // Midway Core
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	if (bufa[3] == '1')
	{
		XLaunchNewImage("D:\\MI_1.xbe", NULL);
	}
	if (bufa[3] == '2')
	{
		XLaunchNewImage("D:\\MI_2.xbe", NULL);
	}
		if (bufa[3] == '3')
	{
		XLaunchNewImage("D:\\MI_3.xbe", NULL);
	}
		if (bufa[3] == '4')
	{
		XLaunchNewImage("D:\\MI_4.xbe", NULL);
	}
		if (bufa[3] == '5')
	{
		XLaunchNewImage("D:\\MI_5.xbe", NULL);
	}
			if (bufa[3] == '6')
	{
		XLaunchNewImage("D:\\Doom2.xbe", NULL);
	}
				if (bufa[3] == '7')
	{
		XLaunchNewImage("D:\\DoomFinal.xbe", NULL);
	}
				if (bufa[3] == '8')
	{
		XLaunchNewImage("D:\\DoomFinal2.xbe", NULL);
	}
	  }

	  	  if ( bufa[0] == 'N' && bufa[1] == 'E' && bufa[2] == 'S' && bufa[3] == '_') // NES
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\NEScore.xbe", NULL);
	  }

	  	  if ( bufa[0] == 'L' && bufa[1] == 'Y' && bufa[2] == 'N' && bufa[3] == 'X') // LYNX
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\LYNXcore.xbe", NULL);
	  }

	  	  if (( bufa[0] == 'S' && bufa[1] == 'M' && bufa[2] == 'S' && bufa[3] == '_') || ( bufa[0] == 'G' && bufa[1] == 'G' && bufa[2] == '_') || ( bufa[0] == 'S' && bufa[1] == 'G' && bufa[2] == '_')) // Master System and Gamegear
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\SMScore.xbe", NULL);
	  }

	  	  if (( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == 'A' && bufa[3] == '_') || ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == '_') || ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == 'C' && bufa[3] == '_')) // Gameboys
	  {
				++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				g_romListOptions = GetOptions();
  GetCursorPosition(  &g_persistentLaunchData.m_cursorPosition, 
                              &g_persistentLaunchData.m_pageOffset,
                              &g_persistentLaunchData.m_superscrollIndex );

				SaveROMMetadataFile();
				SaveOptions();
				UpdateSortedList();
				UpdateSortedList();
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      	  
	  	FILE *f;

		f = fopen("D:\\game.txt", "w+");
		fprintf(f, "D:\\roms\\%s.zip\n", driverData.m_romFileName);
		fclose(f);
		XLaunchNewImage("D:\\GBAcore.xbe", NULL);
	  }



if (g_romListOptions.m_rotate == TRUE)
{
	 MAMEoXDriverMetadata_t  &metadata   = m_driverMetadata[GetCurrentGameIndex()];
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = metadata.m_genre[0] ;
	  bufa[1] = metadata.m_genre[1] ;
	  bufa[2] = metadata.m_genre[9] ;
	  bufa[3] = metadata.m_genre[10] ;

	  if (( bufa[0] == 'S' && bufa[1] == 'h' && bufa[2] == 'T' && bufa[3] == 'o') || g_romListOptions.m_onlyrotateshooters == false)
	  {
		if (driverData.m_screenOrientation & ORIENTATION_SWAP_XY)// Ken
			{
				g_rendererOptions.m_screenRotation = SR_90; 
			}
	  }
}

if (g_rendererOptions.m_rotationkeys == TRUE )// Ken2
			{
					MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
				g_rendererOptions.m_screenRotation = SR_270; 
				if (driverData.m_screenOrientation & ORIENTATION_SWAP_XY)// Ken
					{
						g_rendererOptions.m_screenRotation = SR_180; 
					}
			}			
		

	
	g_soundEnabled = TRUE;

		if (m_ROMStatus[GetCurrentGameIndex()] == 2 && ( g_romListOptions.m_autosound == TRUE ))
		{
			g_soundEnabled = FALSE;
		}
				if (m_ROMStatus[GetCurrentGameIndex()] != 2 && ( g_romListOptions.m_autosound == TRUE ))
		{
			g_soundEnabled = TRUE;
		}
				if (g_romListOptions.m_soundlockout == TRUE && ( g_romListOptions.m_autosound == FALSE ))
		{
			g_soundEnabled = FALSE;
		}

			// Run the selected ROM
    if( GetCurrentGameIndex() != INVALID_ROM_INDEX  )
    {
      if( !m_gameSelected )
      {
        m_gameSelected = TRUE;
        ++m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed;
		        PRINTMSG(( T_INFO, "m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed %lu", m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed ));
				SaveROMMetadataFile();
				UpdateSortedList();
				UpdateSortedList();
      }
	 }
	}

//Ebs Favourite Toggle
  else if( gp.IsButtonPressed( GP_WHITE ) && (g_romListOptions.m_fav == FALSE))
  {
    DWORD currentGameIdx = GetCurrentGameIndex();

    if( currentGameIdx != INVALID_ROM_INDEX )
    {
    MAMEoXDriverMetadata_t  &metadata = m_driverMetadata[currentGameIdx];  
	
	if( metadata.m_favoriteStatus == FS_STRONGLIKE )
	{	
		metadata.m_favoriteStatus = FS_INDIFFERENT;
	}
	else
	{
		metadata.m_favoriteStatus = FS_STRONGLIKE;
	}
	}
    gp.WaitForNoButton();
  }

 

// Ken Enabled BACK button to toggle through Sort options
//HK$ add g_romListOptions.m_sortMode to change titlebar
	  else if(( gp.IsButtonPressed( GP_BACK )) && g_romListOptions.m_sortModelock == SM_BYNUMPLAYERS )
	{
		if( m_options.m_sortMode < (SM_LAST - 1) ){
			m_options.m_sortMode = (ROMListSortMode)(m_options.m_sortMode + 1);
			g_romListOptions.m_sortMode=(ROMListSortMode)(g_romListOptions.m_sortMode + 1);
		}
		else{
			m_options.m_sortMode = SM_BYNAME;
			g_romListOptions.m_sortMode =(ROMListSortMode)(0);
		}

    UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();
    gp.WaitForNoButton();
	}


  else if( gp.IsButtonPressed( GP_BLACK ) || gp.IsKeyPressed( VK_SPACE ) && (g_romListOptions.m_fav == FALSE) )
  {
	  
    //No need to regenerate the list, just switch to
    //the noclones (or clones) list
    m_options.m_hideFiltered = !m_options.m_hideFiltered;

    UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();


    gp.WaitForNoButton();

	  }


	  else if(( gp.IsButtonPressed( XINPUT_GAMEPAD_RIGHT_THUMB ) &&  g_romListOptions.m_sortModelock == SM_BYNUMPLAYERS) && g_romListOptions.m_shortcutkey == 1) // Ken Sort by name switch
  {
	 m_options.m_sortMode = SM_BYNUMTIMESPLAYED;
	 g_romListOptions.m_sortMode = SM_BYNUMTIMESPLAYED;
	 m_pageOffset = 0;
	m_cursorPosition = 0;
    UpdateSortedList();
	m_pageOffset = 0;
	m_cursorPosition = 0;
    UpdateSortedList();
    gp.WaitForNoButton();
  }
  	/*  else if((( gp.IsButtonPressed( XINPUT_GAMEPAD_RIGHT_THUMB ) &&  g_romListOptions.m_sortModelock == SM_BYNUMPLAYERS) && g_romListOptions.m_shortcutkey == 1) && m_options.m_sortMode == SM_BYNUMTIMESPLAYED) // Ken Sort by name switch
  {
	  g_romListOptions.m_scalemode = !g_romListOptions.m_scalemode;
	  UpdateSortedList();
	  gp.WaitForNoButton();
  }
  */


	  else if(( gp.IsButtonPressed( XINPUT_GAMEPAD_LEFT_THUMB ) &&  g_romListOptions.m_sortModelock == SM_BYNUMPLAYERS) && g_romListOptions.m_shortcutkey == 1) // Ken Sort by name switch
  {
	m_Random = 1;
	RandomPlayed();
  }
 else if ( !gp.IsButtonPressed( XINPUT_GAMEPAD_LEFT_THUMB ) && (m_Random == 1))
 {
 m_Random = 0;
 }


 

    else if(( gp.IsButtonPressed( GP_X) &&  g_romListOptions.m_sortModelock == SM_BYNUMPLAYERS) && g_romListOptions.m_shortcutkey == 1) // Ken Sort by name switch
  {
	 m_options.m_sortMode = SM_BYNAME;
	 g_romListOptions.m_sortMode = SM_BYNAME;
    UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();
    gp.WaitForNoButton();
  }
      else if(( gp.IsButtonPressed( GP_Y) &&  g_romListOptions.m_sortModelock == SM_BYNUMPLAYERS) && g_romListOptions.m_shortcutkey == 1) // Ken Sort by cat switch
  {
	 m_options.m_sortMode = SM_BYGENRE;
	 g_romListOptions.m_sortMode = SM_BYGENRE;
    UpdateSortedList();
    m_numLinesInList = m_currentSortedList.size();
    gp.WaitForNoButton();
  }
      else if(( gp.IsButtonPressed( GP_B) &&  g_romListOptions.m_sortModelock == SM_BYNUMPLAYERS) && g_romListOptions.m_shortcutkey == 1) // Ken Sort by Manufacturer switch
  {
	  if (g_romListOptions.m_sortMode == SM_BYMANUFACTURER )
	  {
		m_options.m_sortMode = SM_BYROMSTATUS;
		g_romListOptions.m_sortMode = SM_BYROMSTATUS;
		UpdateSortedList();
		m_numLinesInList = m_currentSortedList.size();
		gp.WaitForNoButton();
	  }
	  else
	  {
		m_options.m_sortMode = SM_BYMANUFACTURER;
		g_romListOptions.m_sortMode = SM_BYMANUFACTURER;
		UpdateSortedList();
		m_numLinesInList = m_currentSortedList.size();
		gp.WaitForNoButton();
		}
  }

  

  

  else if( (gp.IsKeyPressed( VK_LEFT )) && m_favoriteStatusChangeDelay == 0.0f )
  {
    DWORD currentGameIdx = GetCurrentGameIndex();
    if( currentGameIdx != INVALID_ROM_INDEX )
    {
      MAMEoXDriverMetadata_t  &metadata = m_driverMetadata[currentGameIdx];
      switch( metadata.m_favoriteStatus )
      {
        // *** FS_INDIFFERENT *** //
      case FS_INDIFFERENT:
        metadata.m_favoriteStatus = FS_DISLIKE;
        break;

        // *** FS_STRONGDISLIKE *** //
      case FS_STRONGDISLIKE:


        // *** FS_DISLIKE *** //
      case FS_DISLIKE:
        metadata.m_favoriteStatus = FS_STRONGDISLIKE;
        break;

        // *** FS_LIKE *** //
      case FS_LIKE:
       metadata.m_favoriteStatus = FS_INDIFFERENT;
        break;
        
      case FS_STRONGLIKE:
          metadata.m_favoriteStatus = FS_LIKE;
        break;
      }

      m_favoriteStatusChangeDelay = DPADCURSORMOVE_TIMEOUT;
    }
  }
  else if( (gp.IsKeyPressed( VK_RIGHT )) && m_favoriteStatusChangeDelay == 0.0f )
  {
    DWORD currentGameIdx = GetCurrentGameIndex();
    if( currentGameIdx != INVALID_ROM_INDEX )
    {
      MAMEoXDriverMetadata_t  &metadata = m_driverMetadata[currentGameIdx];
      switch( metadata.m_favoriteStatus )
      {
        // *** FS_INDIFFERENT *** //
      case FS_INDIFFERENT:
        metadata.m_favoriteStatus = FS_LIKE;
        break;

        // *** FS_STRONGDISLIKE *** //
      case FS_STRONGDISLIKE:
        metadata.m_favoriteStatus = FS_DISLIKE;
        break;

        // *** FS_DISLIKE *** //
      case FS_DISLIKE:
        metadata.m_favoriteStatus = FS_INDIFFERENT;
        break;

        // *** FS_LIKE *** //
      case FS_LIKE:
        // *** FS_STRONGLIKE *** //
      case FS_STRONGLIKE:
        metadata.m_favoriteStatus = FS_STRONGLIKE;
        break;
      }

      m_favoriteStatusChangeDelay = DPADCURSORMOVE_TIMEOUT;
    }
  }

		// General idea taken from XMAME
	static UINT64		lastTime = 0;
	UINT64 curTime = osd_cycles();
	FLOAT elapsedTime = (FLOAT)(curTime - lastTime) / (FLOAT)osd_cycles_per_second();
	if( !lastTime )
	{
			// lastTime isn't valid yet, so wait for the next frame
		lastTime = curTime;
		return;
	}
	lastTime = curTime;

		// Decrement the dpad movement timer
	if( m_dpadCursorDelay > 0.0f )
	{
    BYTE vkArrowKeys[2] = { VK_UP, VK_DOWN };
		m_dpadCursorDelay -= elapsedTime;
    if( m_dpadCursorDelay < 0.0f || 
        (!gp.IsOneOfButtonsPressed( GP_DPAD_UP | GP_DPAD_DOWN | GP_DPAD_LEFT | GP_DPAD_RIGHT | GP_LA_UP | GP_LA_DOWN ) &&
         !gp.IsOneOfKeysPressed( vkArrowKeys, 2 )) )
			m_dpadCursorDelay = 0.0f;
	}

  if( m_favoriteStatusChangeDelay > 0.0f )
  {
    BYTE vkArrowKeys[2] = { VK_LEFT, VK_RIGHT };
		m_favoriteStatusChangeDelay -= elapsedTime;
    if( m_favoriteStatusChangeDelay < 0.0f || 
        (!gp.IsOneOfButtonsPressed( GP_DPAD_LEFT | GP_DPAD_RIGHT) &&
         !gp.IsOneOfKeysPressed( vkArrowKeys, 2 )) )
			m_favoriteStatusChangeDelay = 0.0f;
  }

	

 
	 if( (gp.IsButtonPressed( GP_DPAD_RIGHT ) || gp.IsButtonPressed( GP_DPAD_LEFT )) && !m_superscrollMode )
  {
    m_dpadCursorDelay = 0.0f;
    m_superscrollMode = TRUE;
  }
	 else if( m_superscrollMode && !(gp.IsButtonPressed( GP_DPAD_RIGHT ) || gp.IsButtonPressed( GP_DPAD_LEFT )) )
 {
      //Exit superscrollmode
    m_dpadCursorDelay = 0.0f;
    m_superscrollMode = FALSE;
  }

  if( m_superscrollMode )
    SuperScrollModeMoveCursor( gp, elapsedTime );
  else
    NormalModeMoveCursor( gp, elapsedTime );
}

//---------------------------------------------------------------------
//	SuperScrollModeMoveCursor // Kenny
//---------------------------------------------------------------------
void CROMListScreen::SuperScrollModeMoveCursor( CInputManager &gp, FLOAT elapsedTime )
{
  if (gp.IsOneOfButtonsPressed( GP_DPAD_DOWN | GP_LA_DOWN  | GP_DPAD_RIGHT) && m_dpadCursorDelay == 0.0f )
	{
		m_dpadCursorDelay = DPADCURSORMOVE_TIMEOUT;
    UINT32 startPos = m_currentSuperscrollIndex;

    if (++m_currentSuperscrollIndex >= m_superscrollJumpTable.size() )
      m_currentSuperscrollIndex = 0;
	}
  else if (gp.IsOneOfButtonsPressed( GP_DPAD_UP | GP_LA_UP  | GP_DPAD_LEFT ) && m_dpadCursorDelay == 0.0f )
	{
		m_dpadCursorDelay = DPADCURSORMOVE_TIMEOUT;
    UINT32 startPos = m_currentSuperscrollIndex;

    if( !m_currentSuperscrollIndex )
      m_currentSuperscrollIndex = m_superscrollJumpTable.size() - 1;
    else
      --m_currentSuperscrollIndex;
	}

    // Jump the cursor if there's a place to jump to, and we're not 
    // already in the section starting with the selected superscroll value
  CStdString curVal, curROMVal;
  GetFriendlySuperscrollIndexStringForROM( &curROMVal, GetAbsoluteCursorPosition() );
  GetFriendlySuperscrollIndexStringForJumpTableIndex( &curVal, m_currentSuperscrollIndex );

  if( curVal != curROMVal && curVal != " Scan Your Games " )
    SetAbsoluteCursorPosition( m_superscrollJumpTable[m_currentSuperscrollIndex] );
}

//---------------------------------------------------------------------
//  NormalModeMoveCursor
//---------------------------------------------------------------------
void CROMListScreen::NormalModeMoveCursor( CInputManager &gp, FLOAT elapsedTime )
{
		// General idea taken from XMAME

		// The combined trigger offset, scaled to the range [-1.0f,1.0f]
  FLOAT cursorVelocity = 0.0f;

    // Loop through all the gamepads, checking the right and left triggers
    // until one with an offset is found
  for( UINT32 i = 0; i < 4 && cursorVelocity == 0.0f; ++i )
  {
    CGamepad *gamepad;
    if( (gamepad = gp.GetGamepad( i )) )
      cursorVelocity = (FLOAT)(gamepad->GetAnalogButtonState( GP_RIGHT_TRIGGER ) - gamepad->GetAnalogButtonState( GP_LEFT_TRIGGER ));
  }

  cursorVelocity /= 256.0f;

  if (g_romListOptions.m_dpadfastscroll == false)
  {
  if ( gp.IsOneOfButtonsPressed( GP_LEFT_TRIGGER | GP_RIGHT_TRIGGER ))
	
  {
	  m_FastScroll = 1;
  }
  else
  {
	  m_FastScroll = 0;
  }
  }
    if (g_romListOptions.m_dpadfastscroll == TRUE)
  {
  if ( gp.IsOneOfButtonsPressed( GP_LEFT_TRIGGER | GP_RIGHT_TRIGGER | GP_DPAD_DOWN | GP_DPAD_UP | GP_DPAD_LEFT | GP_DPAD_RIGHT ))
	
  {
	  m_FastScroll = 1;
  }
  else
  {
	  m_FastScroll = 0;
  }
  }

		// Reset the speed band timeout
	if( cursorVelocity < 0.99f && cursorVelocity > -0.99f )
	{
		m_cursorSpeedBandTimeout = 0.0f;
	}

	else
	{
		m_cursorSpeedBandTimeout += elapsedTime;
		if( m_cursorSpeedBandTimeout > SBTIMEOUT_FASTEST )
			m_cursorSpeedBandTimeout = SBTIMEOUT_FASTEST;
	}

			if ( (m_cursorPosition == 14 ) && gp.IsOneOfButtonsPressed( GP_DPAD_DOWN) && m_currentSortedList.size() >= 15 && m_dpadCursorDelay == 0.0f )  // Kenny
			{
				m_pageOffset = 0;
				m_cursorPosition = 0;
				m_dpadCursorDelay = DPADCURSORMOVE_TIMEOUT;
				UpdateSortedList();	
			}

					  		if ((m_cursorPosition == 0 ) && gp.IsOneOfButtonsPressed( GP_DPAD_UP) && m_currentSortedList.size() >= 15 && m_dpadCursorDelay == 0.0f ) // Kenny

			{
				m_pageOffset = m_currentSortedList.size();
				m_cursorPosition = -1;
				m_dpadCursorDelay = DPADCURSORMOVE_TIMEOUT;
				UpdateSortedList();	
			}

	
		// DPAD overrides the triggers
  if( (gp.IsOneOfButtonsPressed( GP_DPAD_DOWN | GP_LA_DOWN ) || gp.IsKeyPressed( VK_DOWN )) && m_dpadCursorDelay == 0.0f )
	{

			// Round the cursor position down to a integer so that adding 1 will move to the next item
    m_pageOffset = (FLOAT)((LONG)m_pageOffset);
		m_cursorPosition = (FLOAT)((LONG)m_cursorPosition);
    cursorVelocity = 1.0f;
		m_dpadCursorDelay = DPADCURSORMOVE_TIMEOUT;
	}

  else if( (gp.IsOneOfButtonsPressed( GP_DPAD_UP | GP_LA_UP ) || gp.IsKeyPressed( VK_UP )) && m_dpadCursorDelay == 0.0f )
	{
				// Round the cursor position down to a integer so that subtracting 1 will move to the next item
    m_pageOffset = (FLOAT)((LONG)m_pageOffset);
		m_cursorPosition = (FLOAT)((LONG)m_cursorPosition);
    cursorVelocity = -1.0f;
		m_dpadCursorDelay = DPADCURSORMOVE_TIMEOUT;
	}
	else
	{
			// Handle the dead zone
		if( cursorVelocity > -DEADZONE && cursorVelocity < DEADZONE )
				return;

	
		// Rescale the cursor velocity to be [-CURSOR_SPEED,CURSOR_SPEED] without the deadzone
    if( cursorVelocity > 0 )
      cursorVelocity -= DEADZONE;
    else
      cursorVelocity += DEADZONE;
		cursorVelocity *= DEADZONE_RECTIFIER;
    cursorVelocity *= CURSOR_SPEED;
	}

	  // Apply speed bands
	if( m_cursorSpeedBandTimeout == SBTIMEOUT_FASTEST )
		cursorVelocity *= SBMULTIPLIER_FASTEST;
	else if( m_cursorSpeedBandTimeout > SBTIMEOUT_FASTER )
		cursorVelocity *= SBMULTIPLIER_FASTER;
	else if( m_cursorSpeedBandTimeout > SBTIMEOUT_FAST )
		cursorVelocity *= SBMULTIPLIER_FAST;


	const CSkinScrollArea *area = g_loadedSkin->GetSkinElementScrollArea( SKINELEMENT_HELPSCREEN_BODY_SCROLLAREA );
	if( area )
		m_maxPageSize = area->GetHeight() / area->m_singleRowHeight;
	else
		m_maxPageSize = 15;

	DWORD pageSize = (m_currentSortedList.size() < m_maxPageSize ? m_currentSortedList.size() : m_maxPageSize);
	ULONG pageHalfwayPoint = (pageSize >> 1);
	ULONG maxPageOffset = m_currentSortedList.size() - pageSize;

	if( cursorVelocity > 0 )
	{

			// Moving down in the list

			// If the cursor position is not locked at the halfway point, move it towards there
		if( (ULONG)m_cursorPosition < pageHalfwayPoint )
		{
				// See if the entire velocity is consumed in moving the cursor or not
			if( (cursorVelocity + m_cursorPosition) < pageHalfwayPoint )
				m_cursorPosition += cursorVelocity;
			else
			{
				cursorVelocity -= ((FLOAT)pageHalfwayPoint - m_cursorPosition);
				m_cursorPosition = (FLOAT)pageHalfwayPoint;
				m_pageOffset += cursorVelocity;
			}
		}
		else
		{
				// The cursor is already at the halfway point

				// If the page offset can be moved without going off the end of the list, do so
			if( (ULONG)(cursorVelocity + m_pageOffset) <= maxPageOffset )
			{
				m_pageOffset += cursorVelocity;
			}
			else
			{

					// See if the entire velocity is consumed in moving the page or not
				if( (cursorVelocity + m_pageOffset) <= (FLOAT)maxPageOffset )
					m_cursorPosition += cursorVelocity;
				else
				{
					cursorVelocity -= ((FLOAT)maxPageOffset - m_pageOffset);
					m_pageOffset = (FLOAT)maxPageOffset;
					m_cursorPosition += cursorVelocity;
				}

			}
		}

			// Cap values
		if( (ULONG)m_pageOffset > maxPageOffset )
			m_pageOffset = (FLOAT)maxPageOffset;
		if( (ULONG)m_cursorPosition > (pageSize - 1) )
			m_cursorPosition = (FLOAT)(pageSize - 1);
	}

	else
	{
			//--- Moving up in the list -----------------------------------------------

			// If the cursor position is not locked at the halfway point, move it towards there
		if( (ULONG)m_cursorPosition > pageHalfwayPoint )
		{
				// See if the entire velocity is consumed in moving the cursor or not
			if( (cursorVelocity + m_cursorPosition) > pageHalfwayPoint )
				m_cursorPosition += cursorVelocity;
			else
			{
				cursorVelocity -= ((FLOAT)pageHalfwayPoint - m_cursorPosition);
				m_cursorPosition = (FLOAT)pageHalfwayPoint;
				m_pageOffset += cursorVelocity;
			}
		}
		else
		{
				// The cursor is already at the halfway point

				// If the page offset can be moved without going off the end of the list, do so
			if( (LONG)(cursorVelocity + m_pageOffset) >= 0 )
			{
				m_pageOffset += cursorVelocity;
			}
			else
			{
					// See if the entire velocity is consumed in moving the page or not
				if( (cursorVelocity + m_pageOffset) >= 0.0f )
					m_cursorPosition += cursorVelocity;
				else
				{
					cursorVelocity += m_pageOffset;
					m_pageOffset = 0.0f;
					m_cursorPosition += cursorVelocity;
				}
			}
		}

			// Cap values
		if( (LONG)m_pageOffset < 0 )
			m_pageOffset = 0.0f;
		if( (LONG)m_cursorPosition < 0 )
			m_cursorPosition = 0.0f;
	}

	

    // If the superscroll index is not set to this ROM, make it so
  CStdString curVal, currentROMVal;
  GetFriendlySuperscrollIndexStringForJumpTableIndex( &curVal, m_currentSuperscrollIndex );

  if( GetCurrentGameIndex() != INVALID_ROM_INDEX )
  {
    GetFriendlySuperscrollIndexStringForROM( &currentROMVal, GetAbsoluteCursorPosition() );
    if( curVal != currentROMVal )
    {
      for( m_currentSuperscrollIndex = 0; m_currentSuperscrollIndex < m_superscrollJumpTable.size(); ++m_currentSuperscrollIndex )
      {
        GetFriendlySuperscrollIndexStringForJumpTableIndex( &curVal, m_currentSuperscrollIndex );

        if( curVal == currentROMVal )
          return;
      }

      PRINTMSG(( T_ERROR, "Could not find valid jump table index for ROM %lu [%s]!", GetCurrentGameIndex(), currentROMVal.c_str() ));
      m_currentSuperscrollIndex = 0;
    }
  }
   	
}


//---------------------------------------------------------------------
//	Draw 
//---------------------------------------------------------------------
void CROMListScreen::Draw( BOOL clearScreen, BOOL flipOnCompletion )
{

    m_numLinesInList = m_currentSortedList.size();


  if( clearScreen )  
	  m_displayDevice->Clear(	0L,																// Count
		  											NULL,															// Rects to clear
			  										D3DCLEAR_TARGET,	                // Flags
				  									D3DCOLOR_XRGB(0,0,0),							// Color
					  								1.0f,															// Z
						  							0L );															// Stencil

	if( !g_loadedSkin )
		return;

    // Render the backdrop texture
  RenderBackdrop();

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_FOOTER ) )
		g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_FOOTER )->Render( m_displayDevice );

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY ) )
		g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_BODY )->Render( m_displayDevice );

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER ) )
		g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_HEADER )->Render( m_displayDevice );





		// ** A ** //
	//if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_A) )
		//g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_A)->Render( m_displayDevice, L"  " );

		// ** X ** //
//	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_X) && g_romListOptions.m_items == TRUE )
//		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_X)->Render( m_displayDevice, L"  " );


		// ** Y ** //
	if((( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_BLACK) ) && m_options.m_hideFiltered && (g_romListOptions.m_fav == FALSE)) && g_romListOptions.m_nobuttons == false)
		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_Y)->Render( m_displayDevice, L"" );


		// ** Start ** //
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_START) )
		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_START)->Render( m_displayDevice, L"Options" );

	//ebs B BUTTON
	if(( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_B) && (g_romListOptions.m_fav == FALSE)) && g_romListOptions.m_nobuttons == false)
		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_WHITE)->Render( m_displayDevice, L"On/Off Favorite Game" );


	//ebs BACK BUTTON
	if(( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_BACK) )  && g_romListOptions.m_sortModelock == SM_BYNUMPLAYERS)
	{
		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_BACK)->Render( m_displayDevice, L" " );
	}
		if(( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_BACK) )  && g_romListOptions.m_sortModelock != SM_BYNUMPLAYERS)
	{
		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_START)->Render( m_displayDevice, L" " );
	}

	//ebs black button
	if((( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_BLACK) ) && m_options.m_hideFiltered && (g_romListOptions.m_fav == FALSE)) && g_romListOptions.m_nobuttons == false)
		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_BLACK)->Render( m_displayDevice, L"View All Games" );

		if((( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_BLACK) ) && !m_options.m_hideFiltered && (g_romListOptions.m_fav == FALSE)) && g_romListOptions.m_nobuttons == false)
		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_BLACK)->Render( m_displayDevice, L"View Favorite Games" );




  m_displayDevice->SetRenderState( D3DRS_ALPHABLENDENABLE,    FALSE );
  m_displayDevice->SetTexture( 0, NULL );


  if( GetCurrentGameIndex() != INVALID_ROM_INDEX )
  {
    switch( m_options.m_displayMode )
    {
      // *** DM_VERBOSELIST *** //
    case DM_VERBOSELIST:
			{
					// Draw the dividers
				FLOAT headerLeft = 0.0f;
				FLOAT headerTop = 0.0f;
				if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER ) )
				{
					const CSkinElement *bodyArea = g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_HEADER );
					headerLeft = bodyArea->m_left;
					headerTop = bodyArea->m_top;
				}

				if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_MANUFACTURER_DIVIDER ) )
				{
					g_loadedSkin->GetSkinElementDivider(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_MANUFACTURER_DIVIDER)->RenderAsOffset( m_displayDevice,
																																																														headerLeft,
																																																														headerTop );
				}

				if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_YEAR_DIVIDER ) )
				{
					g_loadedSkin->GetSkinElementDivider(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_YEAR_DIVIDER)->RenderAsOffset( m_displayDevice,
																																																														headerLeft,
																																																														headerTop );
				}

				if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_NUMPLAYERS_DIVIDER ) )
				{
					g_loadedSkin->GetSkinElementDivider(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_NUMPLAYERS_DIVIDER)->RenderAsOffset( m_displayDevice,
																																																														headerLeft,
																																																														headerTop );
				}

				if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_CLONE_DIVIDER ) )
				{
					g_loadedSkin->GetSkinElementDivider(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_CLONE_DIVIDER)->RenderAsOffset( m_displayDevice,
																																																														headerLeft,
																																																														headerTop );
				}

				DrawVerboseList();
			}
      break;

      // *** DM_SIMPLELIST *** //
    case DM_SIMPLELIST:
      DrawSimpleList();
      break;

      // *** DM_DETAILED *** //
    case DM_DETAILED:
      DrawDetailedList();
      break;
    }
  }


    //-- Render the scroll up and/or scroll down icons --------------------------------------------
	// FLOAT pageSize = GetCurrentPageSize();
	// if( (UINT32)m_pageOffset && CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLICON_UP ) )
	//	g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLICON_UP )->Render( m_displayDevice );

	//if( (UINT32)m_pageOffset < (m_numLinesInList - (UINT32)pageSize) && CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLICON_DOWN ) )
	//	g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLICON_DOWN )->Render( m_displayDevice );

	if( flipOnCompletion )
	  m_displayDevice->Present( NULL, NULL, NULL, NULL );	
}


//---------------------------------------------------------------------
//	DrawVerboseList
//---------------------------------------------------------------------
void CROMListScreen::DrawVerboseList( void )
{
	if( !CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA ) )
	{
		PRINTMSG(( T_ERROR, "SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA invalid!" ));
		return;
	}

	const CSkinScrollArea *area = g_loadedSkin->GetSkinElementScrollArea( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA );

	WCHAR name[512];
	FLOAT selectedItemYPos = area->m_top + (area->m_singleRowHeight * (ULONG)m_cursorPosition);

	if( area->m_highlightBar )
		area->m_highlightBar->RenderAsOffset( m_displayDevice, area->m_left, selectedItemYPos );

    // Draw the dividers
	FLOAT bodyLeft = 0.0f;
	FLOAT bodyTop = 0.0f;
	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY ) )
	{
		const CSkinElement *bodyArea = g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_BODY );
		bodyLeft = bodyArea->m_left;
		bodyTop = bodyArea->m_top;
	}

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_VERBOSE_MANUFACTURER_DIVIDER ) )
	{
		g_loadedSkin->GetSkinElementDivider(SKINELEMENT_ROMLISTSCREEN_BODY_VERBOSE_MANUFACTURER_DIVIDER)->RenderAsOffset( m_displayDevice,
																																																											bodyLeft,
																																																											bodyTop );
	}

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_VERBOSE_YEAR_DIVIDER ) )
	{
		g_loadedSkin->GetSkinElementDivider(SKINELEMENT_ROMLISTSCREEN_BODY_VERBOSE_YEAR_DIVIDER)->RenderAsOffset( m_displayDevice,
																																																											bodyLeft,
																																																											bodyTop );
	}

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_VERBOSE_NUMPLAYERS_DIVIDER ) )
	{
		g_loadedSkin->GetSkinElementDivider(SKINELEMENT_ROMLISTSCREEN_BODY_VERBOSE_NUMPLAYERS_DIVIDER)->RenderAsOffset( m_displayDevice,
																																																											bodyLeft,
																																																											bodyTop );
	}

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_VERBOSE_CLONE_DIVIDER ) )
	{
		g_loadedSkin->GetSkinElementDivider(SKINELEMENT_ROMLISTSCREEN_BODY_VERBOSE_CLONE_DIVIDER)->RenderAsOffset( m_displayDevice,
																																																											bodyLeft,
																																																											bodyTop );
	}

//HK$ rewroted
  static WCHAR *sortMode[] = {  L"Sort by Name ", 
                                L"Sort by Year of release ",
                                L"Sort by Times played ", 
								L"Sort by Type ",
								L"Sort by Manufacturer ",
                                L"Sort by Arcade or Home " ,
								L"Sort by Console " ,
                                L"Sort by Number of Players " };

  swprintf( name, L"%s  ", sortMode[(UINT32)g_romListOptions.m_sortMode] );
//	swprintf( name, L"Names (%s)  ", m_options.m_hideFiltered ? L"Filtered " : L"Full List" );


  
      // Ken Display the superscroll character
    WCHAR displayString[64] = L"";
    CStdString tempBuf;
    GetFriendlySuperscrollIndexStringForJumpTableIndex( &tempBuf, m_currentSuperscrollIndex );

    mbstowcs( displayString, tempBuf.c_str(), 64 );
	swprintf( &name[wcslen(name)], L":: %s ::", displayString );
  

	FLOAT titleBarLeft = 0.0f;
	FLOAT titleBarTop = 0.0f;
	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER ) )
	{
		const CSkinElement *titleBarArea = g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_HEADER );
		titleBarLeft = titleBarArea->m_left;
		titleBarTop =  titleBarArea->m_top;
	}

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_NAME_TEXT ) )
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_NAME_TEXT)->RenderAsOffset( m_displayDevice, name, titleBarLeft, titleBarTop );

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_MANUFACTERER_TEXT ) )
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_MANUFACTERER_TEXT)->RenderAsOffset( m_displayDevice, L"Manufacturer", titleBarLeft, titleBarTop );

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_YEAR_TEXT ) )
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_YEAR_TEXT)->RenderAsOffset( m_displayDevice, L"Year", titleBarLeft, titleBarTop );

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_NUMPLAYERS_TEXT ) )
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_NUMPLAYERS_TEXT)->RenderAsOffset( m_displayDevice, L"#P", titleBarLeft, titleBarTop );

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_CLONE_TEXT ) )
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_HEADER_VERBOSE_CLONE_TEXT)->RenderAsOffset( m_displayDevice, L"Clone", titleBarLeft, titleBarTop );


		// Render the ROM info
	FLOAT yPos = area->m_top;
  FLOAT pageSize = GetCurrentPageSize();
	ULONG absListIDX = (ULONG)m_pageOffset;

	for( DWORD i = absListIDX; i < pageSize + absListIDX; ++i )
	{
		if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_ROMWORKING_NAME_TEXT ) )
		{
			const CSkinText *nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_ROMWORKING_NAME_TEXT);

//			ebs favourite color HK$ fixed 
			MAMEoXDriverMetadata_t  &metadata   = m_driverMetadata[m_currentSortedList[i]];
//			ebs favourite color HK$ use option g_romListOptions.m_showFAVERoms
			if ( g_romListOptions.m_showFAVEStatus )
			{
				if ( metadata.m_favoriteStatus == FS_STRONGLIKE )
				{
						if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_FAVE_TEXT) )
							nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_FAVE_TEXT);
					}
				else
				{
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_ROMWORKING_NAME_TEXT);
				}
			}

				// Set the ROM color based on its status
			if( m_options.m_showROMStatus )
			{
				ROMStatus &status = m_ROMStatus[m_currentSortedList[i]];
				switch( status )
				{
				case STATUS_UNKNOWN:
				case STATUS_WORKING:
				case STATUS_SLOW:
				default:
						// Do nothing
					break;


				case STATUS_CRASH:
				case STATUS_OUT_OF_MEMORY:
				case STATUS_GENERAL_NONWORKING:
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_ROMNONWORKING_NAME_TEXT)) )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_ROMNONWORKING_NAME_TEXT);
					break;
				}
		
			}

			mbstowcs( name, m_driverInfoList[ m_currentSortedList[i] ].m_description, 255 );
			nameText->RenderAsOffset( m_displayDevice, name, area->m_left, yPos );
		}

		if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_MANUFACTURER_TEXT ) )
		{
			mbstowcs( name, m_driverInfoList[ m_currentSortedList[i] ].m_manufacturer, 255 );
			g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_MANUFACTURER_TEXT)->RenderAsOffset( m_displayDevice, name, area->m_left, yPos );
		}

		if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_YEAR_TEXT ) )
		{
			mbstowcs( name, m_driverInfoList[ m_currentSortedList[i] ].m_year, 255 );
			g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_YEAR_TEXT)->RenderAsOffset( m_displayDevice, name, area->m_left, yPos );
		}

		if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_NUMPLAYERS_TEXT ) )
		{
			swprintf( name, L"%lu", m_driverInfoList[m_currentSortedList[i]].m_numPlayers );
			g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_NUMPLAYERS_TEXT)->RenderAsOffset( m_displayDevice, name, area->m_left, yPos );
		}

		if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_CLONE_TEXT ) )
		{
			mbstowcs( name, m_driverInfoList[ m_currentSortedList[i] ].m_cloneFileName, 255 );
			g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_CLONE_TEXT)->RenderAsOffset( m_displayDevice, name, area->m_left, yPos );
		}

			// Inc the Y position
		yPos += area->m_singleRowHeight;
	}
}

//---------------------------------------------------------------------
//	DrawSimpleList // Kenny
//---------------------------------------------------------------------
void CROMListScreen::DrawSimpleList( void )
{
	if( !CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA ) )
	{
		PRINTMSG(( T_ERROR, "SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA invalid!" ));
		return;
	}


	WCHAR name[512];
	WCHAR temp[512];
	WCHAR cat[512];
	WCHAR tem[512];
	

	//Ebs Added this line from "detailed view" routine to enable screenshots to retain
	//Aspect ratio
	 MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
	 MAMEoXDriverMetadata_t  &metadata   = m_driverMetadata[GetCurrentGameIndex()];





 

	// Draw the title bar
  static WCHAR *sortMode[] = {  L"Sort by Name ", 
                                L"Sort by Year of release ",
                                L"Sort by Times played ", 
								L"Sort by Type ",
								L"Sort by Manufacturer ",
                                L"Sort by Arcade or Home " ,
								L"Sort by Console " ,
                                L"Sort by Number of Players " };

  swprintf( name, L"%s  ", sortMode[(UINT32)g_romListOptions.m_sortMode]);
        // Ken Display the superscroll character
  // if ( ( m_options.m_sortMode > 0 ) || (  m_superscrollMode ) )
  //  {

		WCHAR displayString[64] = L"";
    CStdString tempBuf;
    GetFriendlySuperscrollIndexStringForJumpTableIndex( &tempBuf, m_currentSuperscrollIndex );
    mbstowcs( displayString, tempBuf.c_str(), 64 );
	swprintf( &name[wcslen(name)], L":: %s ::", displayString );
// }


	if (g_romListOptions.m_showposition == TRUE)
	{
  	  if  (m_ROMListFull.size() != m_currentSortedList.size())
	  {
	WCHAR displayString[64] = L"";
    CStdString tempBuf;
    GetFriendlySuperscrollIndexStringForJumpTableIndex( &tempBuf, m_currentSuperscrollIndex );
    mbstowcs( displayString, tempBuf.c_str(), 64 );
	swprintf( &name[wcslen(name)], L"   %lu of %lu", GetAbsoluteCursorPosition() + 1, m_currentSortedList.size());
	  }

      if  (m_ROMListFull.size() == m_currentSortedList.size()) // Ken show total games
	  {
	WCHAR displayString[64] = L"";
    CStdString tempBuf;
    GetFriendlySuperscrollIndexStringForJumpTableIndex( &tempBuf, m_currentSuperscrollIndex );
    mbstowcs( displayString, tempBuf.c_str(), 64 );
	swprintf( &name[wcslen(name)], L"   %lu of %lu Games", GetAbsoluteCursorPosition() + 1, m_ROMListFull.size());
	  }
	}
		if (g_romListOptions.m_showposition == FALSE)
	{
  	  if  (m_ROMListFull.size() != m_currentSortedList.size())
	  {
	WCHAR displayString[64] = L"";
    CStdString tempBuf;
    GetFriendlySuperscrollIndexStringForJumpTableIndex( &tempBuf, m_currentSuperscrollIndex );
    mbstowcs( displayString, tempBuf.c_str(), 64 );
	swprintf( &name[wcslen(name)], L"   %lu", m_currentSortedList.size());
	  }

      if  (m_ROMListFull.size() == m_currentSortedList.size()) // Ken show total games
	  {
	WCHAR displayString[64] = L"";
    CStdString tempBuf;
    GetFriendlySuperscrollIndexStringForJumpTableIndex( &tempBuf, m_currentSuperscrollIndex );
    mbstowcs( displayString, tempBuf.c_str(), 64 );
	swprintf( &name[wcslen(name)], L"   %lu Games", m_ROMListFull.size());
	  }
	}



if (g_romListOptions.m_top && g_romListOptions.m_hot)
{
  wcscat( name, m_options.m_hideFiltered ? L" Hot and Favorite Games" : L"  " );
}
if (g_romListOptions.m_top && !g_romListOptions.m_hot)
{
  wcscat( name, m_options.m_hideFiltered ? L" Classic and Favorite Games" : L"  " );
}
if (!g_romListOptions.m_top && g_romListOptions.m_hot)
{
  wcscat( name, m_options.m_hideFiltered ? L" Hot and Favorite Games" : L"  " );
}
if (!g_romListOptions.m_top && !g_romListOptions.m_hot)
{
  wcscat( name, m_options.m_hideFiltered ? L" Favorite Games" : L"  " );
}




  



	FLOAT titleBarLeft = 0.0f;
	FLOAT titleBarTop = 0.0f;
	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER ) )
	{
		const CSkinElement *titleBarArea = g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_HEADER );
		titleBarLeft = titleBarArea->m_left;
		titleBarTop =  titleBarArea->m_top;
	}

	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER_SIMPLE_NAME_TEXT ) )
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_HEADER_SIMPLE_NAME_TEXT)->RenderAsOffset( m_displayDevice, name, titleBarLeft, titleBarTop );



	const CSkinScrollArea *area = g_loadedSkin->GetSkinElementScrollArea( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA );
	FLOAT selectedItemYPos = area->m_top + (area->m_singleRowHeight * (ULONG)m_cursorPosition);



	    // Sort of a hack, keep track of the last selected ROM
    // so we can load a screenshot file whenever we change to
    // a new ROM
  static UINT32 lastGameIndex = INVALID_ROM_INDEX;
  static UINT32 lastScreenshotIndex = 0;
  m_ForcePic = 0;
  if ( GetCurrentGameIndex() != lastGameIndex && ( m_FastScroll == 0))
  {
    lastGameIndex = GetCurrentGameIndex();
	stopMovie();
      // Display the screenshot if there is one
    LoadScreenshotFile( 0 );
	if (m_Random == 1)
	{
	m_ForcePic = 1;
	}
  }


	if ((driverData.m_screenOrientation & ORIENTATION_SWAP_XY) && g_romListOptions.m_stretchscreenshot == false )// Ken video previews pull skin sizes
	{
  if( CheckResourceValidity(SKINELEMENT_SKINCHOOSERSCREEN_BODY_SCROLLAREA_SINGLEROW_SCREENSHOT) )
	{
		const CSkinScreenshot *screenshot = g_loadedSkin->GetSkinElementScreenshot(SKINELEMENT_SKINCHOOSERSCREEN_BODY_SCROLLAREA_SINGLEROW_SCREENSHOT);
                        fLeft = screenshot->m_left;
                        fTop = screenshot->m_top;
						fRight = screenshot->m_right;
						fBottom = screenshot->m_bottom;
	  	const CSkinElement *bodyArea = g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_BODY ); // add body area works by itslef
		fLeft = fLeft + bodyArea->m_left;
		fTop = fTop + bodyArea->m_top;
		fRight = fRight + bodyArea->m_left;
		fBottom = fBottom + bodyArea->m_top;
	

	}
	}
	else
	{
		  if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_SCREENSHOT) )
	{
		const CSkinScreenshot *screenshot = g_loadedSkin->GetSkinElementScreenshot(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_SCREENSHOT);
                          fLeft = screenshot->m_left;
                        fTop = screenshot->m_top;
						fRight = screenshot->m_right;
						fBottom = screenshot->m_bottom;
	  	const CSkinElement *bodyArea = g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_BODY ); // add body area works by itself
		fLeft = fLeft + bodyArea->m_left;
		fTop = fTop + bodyArea->m_top;
		fRight = fRight + bodyArea->m_left;
		fBottom = fBottom + bodyArea->m_top;
	}
	}


/*	if ((driverData.m_screenOrientation & ORIENTATION_SWAP_XY) && g_romListOptions.m_stretchscreenshot == false )// Ken video previews size are aspect corrected if vert and not stretched setting
	{
 if (g_rendererOptions.m_Hidefrunning == FALSE)
 {
	// 154,3,574,322
	fLeft = 105;
	fTop = 126;
	fRight = 535;
	fBottom = 446;
 }

  if (g_rendererOptions.m_Hidefrunning == TRUE)
 {
	// 154,3,574,322
	fLeft = 225;
	fTop = 176;
	fRight = 1055;
	fBottom = 668;
 }
	}
	else   // Ken video previews size makes it always run stretched to fill
		{
 if (g_rendererOptions.m_Hidefrunning == FALSE)
 {
	// 154,3,574,322
	fLeft = 35;
	fTop = 126;
	fRight = 605;
	fBottom = 446;
 }

  if (g_rendererOptions.m_Hidefrunning == TRUE)
 {
	// 154,3,574,322
	fLeft = 85;
	fTop = 176;
	fRight = 1195;
	fBottom = 668;
 }
}*/

	 	if( area->m_highlightBar )
		area->m_highlightBar->RenderAsOffset( m_displayDevice, area->m_left, selectedItemYPos );


	if(videoRender && (m_FastScroll == 0)) 
	{
		drawMovie();
	} // Ken Video Preview ends



 


  if (((videoRender == false) || (m_ForcePic == 1)) && (m_FastScroll == 0))
  {
		if ((driverData.m_screenOrientation & ORIENTATION_SWAP_XY) && g_romListOptions.m_stretchscreenshot == false )
			{
  if( CheckResourceValidity(SKINELEMENT_SKINCHOOSERSCREEN_BODY_SCROLLAREA_SINGLEROW_SCREENSHOT) )
	{
		const CSkinScreenshot *screenshot = g_loadedSkin->GetSkinElementScreenshot(SKINELEMENT_SKINCHOOSERSCREEN_BODY_SCROLLAREA_SINGLEROW_SCREENSHOT);

   // swprintf( name, L"[%lu]", 0 );
		if ( m_screenshotTexture )
			screenshot->RenderAsOffset( m_displayDevice,
																	m_screenshotTexture,
																	m_screenshotRect,
																	area->m_left,
																	area->m_top );
																	// driverData.m_screenOrientation & ORIENTATION_SWAP_XY,
																	// driverData.m_screenOrientation & ORIENTATION_FLIP_X,
																	// driverData.m_screenOrientation & ORIENTATION_FLIP_Y );
																	
	}
			}
		else
						{
  if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_SCREENSHOT) )
	{
		const CSkinScreenshot *screenshot = g_loadedSkin->GetSkinElementScreenshot(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_SCREENSHOT);

   // swprintf( name, L"[%lu]", 0 );
		if ( m_screenshotTexture )
			screenshot->RenderAsOffset( m_displayDevice,
																	m_screenshotTexture,
																	m_screenshotRect,
																	area->m_left,
																	area->m_top );
																	// driverData.m_screenOrientation & ORIENTATION_SWAP_XY,
																	// driverData.m_screenOrientation & ORIENTATION_FLIP_X,
																	// driverData.m_screenOrientation & ORIENTATION_FLIP_Y );
																	
		}
	}
  }



	




								//Ebs Added the driverdata.m lines above ^ for aspect ratio fixing.


if (g_romListOptions.m_rotate == TRUE) // Ken addicon overlays for rotating games
{
	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
      char bufa[3] = {0};
      bufa[0] = metadata.m_genre[0] ;
	  bufa[1] = metadata.m_genre[1] ;
	  bufa[2] = metadata.m_genre[9] ;
	  bufa[3] = metadata.m_genre[10] ;

	  if (( bufa[0] == 'S' && bufa[1] == 'h' && bufa[2] == 'T' && bufa[3] == 'o') || g_romListOptions.m_onlyrotateshooters == false)
	  {
		if (driverData.m_screenOrientation & ORIENTATION_SWAP_XY) // Ken2
			{
				if(CheckResourceValidity( SKINELEMENT_HELPSCREEN_BODY_SCROLLICON_UP ) )
	            g_loadedSkin->GetSkinElement( SKINELEMENT_HELPSCREEN_BODY_SCROLLICON_UP )->Render( m_displayDevice );
			}
	  }
}

if (g_romListOptions.m_rotate == TRUE) // Ken addicon overlays for rotating games
{
				if(CheckResourceValidity( SKINELEMENT_HELPSCREEN_BODY_SCROLLICON_DOWN ) )
	            g_loadedSkin->GetSkinElement( SKINELEMENT_HELPSCREEN_BODY_SCROLLICON_DOWN )->Render( m_displayDevice );
}


	FLOAT yPos = area->m_top;
    FLOAT pageSize = GetCurrentPageSize();
	ULONG absListIDX = (ULONG)m_pageOffset;

	for( DWORD i = absListIDX; i < pageSize + absListIDX; ++i )
	{
		if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWORKING_NAME_TEXT ) )
		{
			const CSkinText *nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWORKING_NAME_TEXT);

//			ebs favourite color HK$ add this too simple mode too  // Kennny
			MAMEoXDriverMetadata_t  &metadata   = m_driverMetadata[m_currentSortedList[i]];
//			ebs favourite color HK$ use option g_romListOptions.m_showFAVERoms
			if ( g_romListOptions.m_showFAVEStatus )
			{
				if ( metadata.m_favoriteStatus == FS_STRONGLIKE )
				{
						if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT) )
							nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);

				}
				else
				{
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWORKING_NAME_TEXT);
				}
			}

		


				// Set the ROM color based on its status
			if( m_options.m_showROMStatus )
			{
				ROMStatus &status = m_ROMStatus[m_currentSortedList[i]];
				switch( status )
				{
				case STATUS_UNKNOWN:
				//case STATUS_WORKING:
				// case STATUS_SLOW:
				// case STATUS_CRASH:
				default:
						// Do nothing
					break;

case STATUS_CRASH:
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT);
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_ROMWORKING_NAME_TEXT);
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
					break;


case STATUS_SLOW:
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_MANUFACTURER_TEXT)) )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_MANUFACTURER_TEXT);
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_MANUFACTURER_TEXT)))
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
					break;

case STATUS_GENERAL_NONWORKING:
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT);
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_ROMWORKING_NAME_TEXT);
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
					break;

case STATUS_WORKING:
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT);
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_VERBOSE_ROMWORKING_NAME_TEXT);
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
					break;

case STATUS_OUT_OF_MEMORY:
			if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMNONWORKING_NAME_TEXT)) )
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMNONWORKING_NAME_TEXT);
				if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMNONWORKING_NAME_TEXT)) && g_romListOptions.m_top )
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_NUMPLAYERS_TEXT);
				if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMNONWORKING_NAME_TEXT)) && g_romListOptions.m_top )
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
					


					break;
				}
			}

			else
			{
				ROMStatus &status = m_ROMStatus[m_currentSortedList[i]];
				switch( status )
				{
				case STATUS_UNKNOWN:
				//case STATUS_WORKING:
				case STATUS_SLOW:
				// case STATUS_CRASH: // Ken
				default:
						// Do nothing
					break;

				case STATUS_CRASH:
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_FILENAME_TEXT);
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
					break;

				case STATUS_GENERAL_NONWORKING:
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_FILENAME_TEXT);
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
					break;

				case STATUS_OUT_OF_MEMORY:
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMNONWORKING_NAME_TEXT)) && g_romListOptions.m_top )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_FILENAME_TEXT);
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMNONWORKING_NAME_TEXT)) && g_romListOptions.m_top )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
				
					break;

				case STATUS_WORKING:
					if (metadata.m_favoriteStatus != FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_FILENAME_TEXT);
					if (metadata.m_favoriteStatus == FS_STRONGLIKE && ( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_ROMWARNING_NAME_TEXT)) && g_romListOptions.m_hot )
						nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_SIMPLE_FAVE_TEXT);
					break;
				}
			}



			 mbstowcs( name , m_driverInfoList[ m_currentSortedList[i] ].m_description, 255 );

			 	  				/* WCHAR type[512];

								 			if (m_ROMStatus[m_currentSortedList[i]] == 5 && g_romListOptions.m_showclassic == TRUE)
					{
						mbstowcs( type, metadata.m_genre, 255 );
						swprintf( &name[wcslen(name)], L"*", type );
					}
							if (m_ROMStatus[m_currentSortedList[i]] == 4 && g_romListOptions.m_showclassic == TRUE)
					{
						mbstowcs( type, metadata.m_genre, 255 );
						swprintf( &name[wcslen(name)], L"**", type );
					} */ 


								 	/*	if (g_romListOptions.m_rotate == TRUE && g_romListOptions.m_showgun == TRUE)
		{
			MAMEoXDriverMetadata_t  &metadata   = m_driverMetadata[m_currentSortedList[i]];
			MAMEDriverData_t        &driverData = m_driverInfoList[m_currentSortedList[i]];
			char bufa[3] = {0};
			bufa[0] = metadata.m_genre[0] ;
			bufa[1] = metadata.m_genre[1] ;
			bufa[2] = metadata.m_genre[9] ;
			bufa[3] = metadata.m_genre[10] ;

			if (( bufa[0] == 'S' && bufa[1] == 'h' && bufa[2] == 'T' && bufa[3] == 'o') || g_romListOptions.m_onlyrotateshooters == false)
				{
					if (driverData.m_screenOrientation & ORIENTATION_SWAP_XY)// Ken
						{
								mbstowcs( type, metadata.m_genre, 255 );
								swprintf( &name[wcslen(name)], L" :: ROTATED", type );
						}
				}
		} */
	//	if (m_ROMStatus[m_currentSortedList[i]] == 2 && g_romListOptions.m_shownosound == TRUE)
	//				{
	//					mbstowcs( type, metadata.m_genre, 255 );
	//					swprintf( &name[wcslen(name)], L" (SNES)", type );
	//				}

	if (g_romListOptions.m_asterix == TRUE)
	 {
		WCHAR type[512];
		MAMEDriverData_t        &driverData = m_driverInfoList[m_currentSortedList[i]];
		char bufa[1] = {0};
		bufa[0] = driverData.m_year[0] ;
		if (bufa[0] == 'H') // Ken 
			{
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"*", type );
			}
	 }
	 	if (g_rendererOptions.m_console == TRUE)
	 {
WCHAR type[512];
		MAMEDriverData_t        &driverData = m_driverInfoList[m_currentSortedList[i]];
      char bufa[3] = {0};
      bufa[0] = driverData.m_romFileName[0] ;
	  bufa[1] = driverData.m_romFileName[1] ;
	  bufa[2] = driverData.m_romFileName[2] ;
	  bufa[3] = driverData.m_romFileName[3] ;


	  if ( bufa[0] == 'S' && bufa[1] == 'N' && bufa[2] == 'E' && bufa[3] == 'S') // Ken SNES
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Super Nintendo )", type );
	  }
	 	  if ( bufa[0] == 'M' && bufa[1] == 'D' && bufa[2] == 'R' && bufa[3] == 'I') // Ken Megadrive
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Megadrive )", type );
	  }
	  	 	  if ( bufa[0] == 'L' && bufa[1] == 'Y' && bufa[2] == 'N' && bufa[3] == 'X') // Ken Lynx
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Atari Lynx )", type );
	  }
	  	 	  if ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == '_') // Ken Gameboy
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Gameboy )", type );
	  }
	  	 	  if ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == 'C' && bufa[3] == '_') // Ken Gameboy Color
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Gameboy Color )", type );
	  }
	  	 	  if ( bufa[0] == 'G' && bufa[1] == 'B' && bufa[2] == 'A' && bufa[3] == '_') // Ken Gameboy Advance
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Gameboy Advance )", type );
	  }
	  	 	  if ( bufa[0] == 'P' && bufa[1] == 'C' && bufa[2] == 'E' && bufa[3] == '_') // Ken PC Engine
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( PC Engine )", type );
	  }
	  	  	 	  if ( bufa[0] == 'P' && bufa[1] == 'C' && bufa[2] == 'D' && bufa[3] == '_') // Ken PC Engine
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( PC Engine )", type );
	  }
	  	  	 	  if ( bufa[0] == 'P' && bufa[1] == 'S' && bufa[2] == 'X' && bufa[3] == '_') // Ken Playstation
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Playstation )", type );
	  }
	  	  	  	 	  if ( bufa[0] == 'C' && bufa[1] == '6' && bufa[2] == '4' && bufa[3] == '_') // Ken C64
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Commodore 64 )", type );
	  }
	  	  	  	  	 	  if ( bufa[0] == 'X' && bufa[1] == 'B' && bufa[2] == 'O' && bufa[3] == 'X') // Ken XBOX
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( XBOX )", type );
	  }
	  	  	  	  	  	 	  if ( bufa[0] == 'N' && bufa[1] == '6' && bufa[2] == '4'&& bufa[3] == '_') // Ken N64
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Nintendo 64 )", type );
	  }
	  	 	  if ( bufa[0] == 'N' && bufa[1] == 'E' && bufa[2] == 'S' && bufa[3] == '_') // Ken NES
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( NES )", type );
	  }
	  	 	  if ( bufa[0] == 'S' && bufa[1] == 'M' && bufa[2] == 'S' && bufa[3] == '_') // Ken Master System
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Master System )", type );
	  }
	  	 	  if ( bufa[0] == 'G' && bufa[1] == 'G' && bufa[2] == '_') // Ken Game Gear
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Game Gear )", type );
	  }
	  	  	 	  if ( bufa[0] == 'S' && bufa[1] == 'G' && bufa[2] == '_') // Ken Sega SG-1000
	  {
			mbstowcs( type, driverData.m_romFileName, 255 );
			swprintf( &name[wcslen(name)], L"  ( Sega SG-1000 )", type );
	  }
	 }

      WCHAR displayString[64] = L"";
      CStdString tempBuf;

    //  GetFriendlySuperscrollIndexStringForJumpTableIndex( &tempBuf, m_currentSuperscrollIndex );

mbstowcs( displayString, "", 255 ); // rom list

if (g_romListOptions.m_scalemode == TRUE && g_rendererOptions.m_fastsave == FALSE)
{
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 0)
{
	mbstowcs( displayString, "", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 1)
{
	mbstowcs( displayString, " ::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 2)
{
	mbstowcs( displayString, " :::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 3)
{
	mbstowcs( displayString, " ::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 4)
{
	mbstowcs( displayString, " :::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 5)
{
	mbstowcs( displayString, " ::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 6)
{
	mbstowcs( displayString, " :::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 7)
{
	mbstowcs( displayString, " ::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 8)
{
	mbstowcs( displayString, " :::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 9)
{
	mbstowcs( displayString, " ::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 10)
{
	mbstowcs( displayString, " :::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 11)
{
	mbstowcs( displayString, " ::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 12)
{
	mbstowcs( displayString, " :::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 13)
{
	mbstowcs( displayString, " ::::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 14)
{
	mbstowcs( displayString, " :::::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 15)
{
	mbstowcs( displayString, " ::::::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 16)
{
	mbstowcs( displayString, " :::::::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 17)
{
	mbstowcs( displayString, " ::::::::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 18)
{
	mbstowcs( displayString, " :::::::::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed == 19)
{
	mbstowcs( displayString, " ::::::::::::::::::::", 255 ); // rom list
}
if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed >= 20)
{
	mbstowcs( displayString, " ::::::::::::::::::::: ::", 255 ); // rom list
}
  swprintf( &name[wcslen(name)], L"%s", displayString );

  if (m_driverMetadata[ m_currentSortedList[i] ].m_timesPlayed >= 20 && g_romListOptions.m_removeplaycount == 1) // Ken2
  swprintf( &name[wcslen(name)], L"  %lu", metadata.m_timesPlayed );

}

	


					nameText->RenderAsOffset( m_displayDevice, name, area->m_left, yPos );
		}

			if (g_romListOptions.m_items == TRUE)   // Ken2  Mute
			 {
				if ((m_ROMStatus[GetCurrentGameIndex()] == 2) && (g_romListOptions.m_autosound == TRUE)) 
					{
						if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_A))
						g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_A)->Render( m_displayDevice, L" " );
					}


					if ((g_romListOptions.m_soundlockout == TRUE) && (g_romListOptions.m_autosound == FALSE))  
					 {
						if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_A))
						g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_A)->Render( m_displayDevice, L" " );
					}



	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_X))
		g_loadedSkin->GetSkinElementButtonInfo(SKINELEMENT_ROMLISTSCREEN_BUTTONINFO_X)->Render( m_displayDevice, L"  " );


 
	      //--- Display the genre ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_GENRE_TEXT) )
	{
    if( metadata.m_genre )
      mbstowcs( tem, metadata.m_genre, 255 );
    else
      wcscpy( tem, L" " );
    swprintf( cat, L"%s", tem );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_GENRE_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	cat,
																																																																	area->m_left,
																																																																	area->m_top );
	}





	  	       //--- Display the year ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_YEAR_TEXT) )
	{
    if( driverData.m_year )
      mbstowcs( temp, driverData.m_year, 255 );
    else
      wcscpy( temp, L" " );
    swprintf( name, L"%s", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_YEAR_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}

      //--- Times played ---------------------------------------------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_TIMESPLAYED_TEXT) )
	{
   if( driverData.m_manufacturer )
      mbstowcs( temp, driverData.m_manufacturer, 255 );
    else
      wcscpy( temp, L" " );
    swprintf( name, L"%s", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_TIMESPLAYED_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}

	      //--- Display the parent ROM ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_PARENT_TEXT) && g_rendererOptions.m_fastsave == FALSE )
	{
   	   // swprintf( name, L"%lu Times Played", metadata.m_timesPlayed ); // Ken
		if (m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed != 0)
		{
		if (m_driverMetadata[GetCurrentGameIndex()].m_timesPlayed == 1)
		  swprintf( name, L"              %lu Play", metadata.m_timesPlayed ); // Ken
		else
			swprintf( name, L"              %lu Plays", metadata.m_timesPlayed ); // Ken
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_PARENT_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}
	}
	

	



	
	}	// Render the ROM info // Ken


			// Inc the Y position
		yPos += area->m_singleRowHeight;  // Ken
	}


}

//---------------------------------------------------------------------
//	DrawDetailedList
//---------------------------------------------------------------------
void CROMListScreen::DrawDetailedList( void )
{
	if( !CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA ) )
	{
		PRINTMSG(( T_ERROR, "SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA invalid!" ));
		return;
	}

	const CSkinScrollArea *area = g_loadedSkin->GetSkinElementScrollArea( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA );

	WCHAR name[256];
  WCHAR temp[256];

	MAMEDriverData_t        &driverData = m_driverInfoList[GetCurrentGameIndex()];
  ROMStatus               &status     = m_ROMStatus[GetCurrentGameIndex()];
  MAMEoXDriverMetadata_t  &metadata   = m_driverMetadata[GetCurrentGameIndex()];


    // Sort of a hack, keep track of the last selected ROM
    // so we can load a screenshot file whenever we change to
    // a new ROM
  static UINT32 lastGameIndex = INVALID_ROM_INDEX;
  static UINT32 lastScreenshotIndex = 0;
  if( GetCurrentGameIndex() != lastGameIndex )
  {
    lastGameIndex = GetCurrentGameIndex();


      // Display the screenshot if there is one
      // Todo: mode to display full screen screenshots
    LoadScreenshotFile( 0 );
  }


	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_SCREENSHOT) )
	{
		const CSkinScreenshot *screenshot = g_loadedSkin->GetSkinElementScreenshot(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_SCREENSHOT);

    //swprintf( name, L"[%lu]", 0 );
		if ( m_screenshotTexture )
			screenshot->RenderAsOffset( m_displayDevice,
																	m_screenshotTexture,
																	m_screenshotRect,
																	area->m_left,
																	area->m_top,
																	driverData.m_screenOrientation & ORIENTATION_SWAP_XY,
																	driverData.m_screenOrientation & ORIENTATION_FLIP_X,
																	driverData.m_screenOrientation & ORIENTATION_FLIP_Y );
	}

	FLOAT titleBarLeft = 0.0f;
	FLOAT titleBarTop = 0.0f;
	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_HEADER ) )
	{
		const CSkinElement *titleBarArea = g_loadedSkin->GetSkinElement( SKINELEMENT_ROMLISTSCREEN_HEADER );
		titleBarLeft = titleBarArea->m_left;
		titleBarTop =  titleBarArea->m_top;
	}

	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_HEADER_DETAIL_NAME_TEXT) )
	{
	  mbstowcs( name, driverData.m_description, 255 );

	        // Ken Display the superscroll character
			 if ( ( m_options.m_sortMode > 0 ) || (  m_superscrollMode ) )
    {
      WCHAR displayString[64] = L"";
      CStdString tempBuf;
      GetFriendlySuperscrollIndexStringForJumpTableIndex( &tempBuf, m_currentSuperscrollIndex );

      mbstowcs( displayString, tempBuf.c_str(), 64 );
		  swprintf( &name[wcslen(name)], L"   [%s]", displayString );
}

	  wcscat( name, m_options.m_hideFiltered ? L"     Favorites only" : L"  " );

    
   

		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_HEADER_DETAIL_NAME_TEXT)->RenderAsOffset( m_displayDevice, name, titleBarLeft, titleBarTop );
	}



		// Render the ROM info
	if( CheckResourceValidity( SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMWORKING_NAME_TEXT ) )
	{
		const CSkinText *nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMWORKING_NAME_TEXT);
		swprintf( name, L"ROM Status: " );

			// Set the ROM color based on its status
		if( m_options.m_showROMStatus )
		{
			switch( status )
			{
				// *** STATUS_UNKNOWN *** //
			case STATUS_UNKNOWN:
			default:
				wcscat( name, L"Unknown" );
				break;

				// *** STATUS_WORKING *** //
			case STATUS_WORKING:
				wcscat( name, L"Working" );
				break;

				// *** STATUS_SLOW *** //
			case STATUS_SLOW:
				wcscat( name, L"Runs slowly" );
				if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMWARNING_NAME_TEXT) )
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMWARNING_NAME_TEXT);
				break;

				// *** STATUS_CRASH *** //
			case STATUS_CRASH:
				wcscat( name, L"Crashes" );
				if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMNONWORKING_NAME_TEXT) )
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMNONWORKING_NAME_TEXT);
				break;

				// *** STATUS_OUT_OF_MEMORY *** //
			case STATUS_OUT_OF_MEMORY:
				wcscat( name, L"Out of memory" );
				if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMNONWORKING_NAME_TEXT) )
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMNONWORKING_NAME_TEXT);
				break;

				// *** STATUS_GENERAL_NONWORKING *** //
			case STATUS_GENERAL_NONWORKING:
				wcscat( name, L"General nonworking" );
				if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMNONWORKING_NAME_TEXT) )
					nameText = g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_ROMNONWORKING_NAME_TEXT);
				break;
			}
		}

		nameText->RenderAsOffset( m_displayDevice, name, area->m_left, area->m_top );
	}

      //--- Display the number of players ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_NUMPLAYERS_TEXT) )
	{
    swprintf( name, L"Number of players: %lu", driverData.m_numPlayers );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_NUMPLAYERS_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}

      //--- Display the manufacturer ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_MANUFACTURER_TEXT) )
	{
    if( driverData.m_manufacturer )
      mbstowcs( temp, driverData.m_manufacturer, 255 );
    else
      wcscpy( temp, L"Unknown" );
    swprintf( name, L"Manufacturer: %s", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_MANUFACTURER_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}


      //--- Display the year ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_YEAR_TEXT) )
	{
    if( driverData.m_year )
      mbstowcs( temp, driverData.m_year, 255 );
    else
      wcscpy( temp, L"Unknown" );
    swprintf( name, L"Year: %s", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_YEAR_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}

      //--- Display the parent ROM ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_PARENT_TEXT) )
	{
    if( driverData.m_cloneFileName )
      mbstowcs( temp, driverData.m_cloneFileName, 255 );
    else
      wcscpy( temp, L"None" );
    swprintf( name, L"Parent ROM filename: %s", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_PARENT_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}

         //--- Display the genre ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_GENRE_TEXT) )
	{
    if( metadata.m_genre )
      mbstowcs( temp, metadata.m_genre, 255 );
    else
      wcscpy( temp, L"Unknown" );
    swprintf( name, L"%s", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_GENRE_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}


      //--- Display the version this rom was added to MAME ---------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_VERSIONADDED_TEXT) )
	{
    if( metadata.m_versionAdded )
      mbstowcs( temp, metadata.m_versionAdded, 255 );
    else
      wcscpy( temp, L"Unknown" );
    swprintf( name, L"Version added: %s", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_VERSIONADDED_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}

      //--- Times played ---------------------------------------------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_TIMESPLAYED_TEXT) )
	{
    swprintf( name, L"Times played: %lu", metadata.m_timesPlayed );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_TIMESPLAYED_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}

      //--- Favorite status ---------------------------------------------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_FAVORITESTATUS_TEXT) )
	{
    switch( metadata.m_favoriteStatus )
    {
      // *** FS_INDIFFERENT *** //
    case FS_INDIFFERENT:
      wcscpy( temp, L"Average" );
      break;

      // *** FS_STRONGDISLIKE *** //
    case FS_STRONGDISLIKE:
      wcscpy( temp, L"Strongly disliked" );
      break;

      // *** FS_DISLIKE *** //
    case FS_DISLIKE:
      wcscpy( temp, L"Disliked" );
      break;

      // *** FS_LIKE *** //
    case FS_LIKE:
      wcscpy( temp, L"Liked" );
      break;

      // *** FS_STRONGLIKE *** //
    case FS_STRONGLIKE:
//Ebs changed 'Strongly liked' to 'Favourite'
      wcscpy( temp, L"Favorite" );
      break;
    }
    swprintf( name, L"Favorite status: %s", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_FAVORITESTATUS_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}

      //--- Filename ---------------------------------------------------------------
	if( CheckResourceValidity(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_FILENAME_TEXT) )
	{
    if( driverData.m_romFileName )
      mbstowcs( temp, driverData.m_romFileName, 255 );
    else
      wcscpy( temp, L"Unknown" );
    swprintf( name, L"ROM filename: %s.zip", temp );
		g_loadedSkin->GetSkinElementText(SKINELEMENT_ROMLISTSCREEN_BODY_SCROLLAREA_SINGLEROW_DETAIL_FILENAME_TEXT)->RenderAsOffset( m_displayDevice,
																																																																	name,
																																																																	area->m_left,
																																																																	area->m_top );
	}
}

//---------------------------------------------------------------------
//  LoadScreenshotFile
//---------------------------------------------------------------------
BOOL CROMListScreen::LoadScreenshotFile( UINT32 index )
{
    // Release the old screenshot data
  SAFE_RELEASE( m_screenshotTexture );

  MAMEDriverData_t &driverData = m_driverInfoList[GetCurrentGameIndex()];


  FILE *ROMvideo;

 if ((g_romListOptions.m_videopreview == TRUE) && (videoRender == false ) && (m_FastScroll == 0))
 {
	 std::string filename = g_FileIOConfig.m_videoPath; // Ken Video Preview starts
  if( driverData.m_isClone ) //Checks if current rom is clone or parent.
	{
		filename += "\\";
		filename += driverData.m_romFileName; //adds the current rom filename to the filename variable
		filename += ".xmv";
		ROMvideo = fopen(filename.c_str(), "r"); //Attempts to open the file in read mode ("r")
		if( ROMvideo != NULL ) 
			{
				fclose(ROMvideo); //If the file exists close the file.
			}
		else
			{
				// If the file doesn't exist, reset 'filename' and use the parent screenshot
				filename = g_FileIOConfig.m_videoPath;
				filename += "\\";
				filename += driverData.m_cloneFileName;
				filename += ".xmv";
			}
	}
else
	{
 	filename = g_FileIOConfig.m_videoPath;
	filename += "\\";
	filename += driverData.m_romFileName;
	filename += ".xmv"; 
	}
initMovie((char*)filename.c_str());
drawMovie();

}



  std::string filename = g_FileIOConfig.m_screenshotPath;
	filename += "\\";



//  if( index )
//  {
//    char num[8];
//    sprintf( num, "$.4s%4.4lu", driverData.m_romFileName, index - 1 );
//    filename += num;
//  }

	//OLD SCREENSHOT CODE

  //EBS Enables Clone Roms to use Parent screenshots.
  //HK$ changes to use option "Use Screenshot of"
/*  if( driverData.m_isClone && g_romListOptions.m_screenshotOf )
      filename += driverData.m_cloneFileName;
  else
    filename += driverData.m_romFileName;
  filename += ".png"; */

FILE *ROMScreenshot;

if( driverData.m_isClone ) //Checks if current rom is clone or parent.
	{
		filename += driverData.m_romFileName; //adds the current rom filename to the filename variable
		filename += ".png";
		ROMScreenshot = fopen(filename.c_str(), "r"); //Attempts to open the file in read mode ("r")
		if( ROMScreenshot != NULL ) 
			{
				fclose(ROMScreenshot); //If the file exists close the file.
			}
		else
			{
				// If the file doesn't exist, reset 'filename' and use the parent screenshot
				filename = g_FileIOConfig.m_screenshotPath;
				filename += "\\";
				filename += driverData.m_cloneFileName;
				filename += ".png";
			}
	}
else
	{
		//If the rom is parent, use its screenshot.
		filename += driverData.m_romFileName;
		filename += ".png"; 
	}


return( LoadPNGToTexture( filename, &m_screenshotTexture, &m_screenshotRect ) );
}

//---------------------------------------------------------------------
//	RemoveCurrentGameIndex
//---------------------------------------------------------------------
BOOL CROMListScreen::RemoveCurrentGameIndex( void )
{
	UINT32 curCursorPos = (ULONG)m_pageOffset + (ULONG)m_cursorPosition;
	std::vector<UINT32>::iterator it = m_currentSortedList.begin();
	for( UINT32 i = 0; i < curCursorPos; ++i )
		++it;


  UINT32 index = (*it);
	m_currentSortedList.erase( it );

    // Remove the item from the full listing
  it = std::find( m_ROMListFull.begin(), m_ROMListFull.end(), index );
  if( it != m_ROMListFull.end() )
    m_ROMListFull.erase( it );

    // Remove the item from the filtered listing
  it = std::find( m_ROMListFiltered.begin(), m_ROMListFiltered.end(), index );
  if( it != m_ROMListFiltered.end() )
    m_ROMListFiltered.erase( it );

    // Write out the new list to file
  if( !SaveROMListFile() )
  {
    PRINTMSG(( T_INFO, "Failed to store the ROM list file!" ));
    return FALSE;
  }

  return TRUE;
}

//---------------------------------------------------------------------
//	GenerateSuperscrollJumpTable
//---------------------------------------------------------------------
BOOL CROMListScreen::MoveCurrentGameToBackupDir( void )
{
  if( Helper_MoveCurrentGameToBackupDir( g_FileIOConfig.m_romPath0 ) ||
      Helper_MoveCurrentGameToBackupDir( g_FileIOConfig.m_romPath1 ) ||
      Helper_MoveCurrentGameToBackupDir( g_FileIOConfig.m_romPath2 ) ||
      Helper_MoveCurrentGameToBackupDir( g_FileIOConfig.m_romPath3 ) )
      return TRUE;
  return FALSE;
}

//---------------------------------------------------------------------
//	Helper_MoveCurrentGameToBackupDir
//---------------------------------------------------------------------
BOOL CROMListScreen::Helper_MoveCurrentGameToBackupDir( CStdString &path )
{
		// Move the currently selected game to the backup dir
	UINT32 romIDX = GetCurrentGameIndex();

    // Don't allow removing from a samba share
  if( path.Left(5) != "smb:\\" )
  {



    std::string oldPath = path + "\\";
    oldPath += m_driverInfoList[romIDX].m_romFileName;
    oldPath += ".zip";

	std::string oldpicPath = g_FileIOConfig.m_screenshotPath;
	oldpicPath += "\\";
    oldpicPath += m_driverInfoList[romIDX].m_romFileName;
    oldpicPath += ".png";


	std::string oldvidPath = g_FileIOConfig.m_videoPath;
	oldvidPath += "\\";
    oldvidPath += m_driverInfoList[romIDX].m_romFileName;
    oldvidPath += ".xmv";


    std::string newPath = g_ROMBackupPath;
    newPath += "\\";
    newPath += m_driverInfoList[romIDX].m_romFileName;
    newPath += ".zip";

	std::string newpicPath = g_ROMBackupPath;
    newpicPath += "\\";
    newpicPath += m_driverInfoList[romIDX].m_romFileName;
    newpicPath += ".png";

	std::string newvidPath = g_ROMBackupPath;
    newvidPath += "\\";
    newvidPath += m_driverInfoList[romIDX].m_romFileName;
    newvidPath += ".xmv";

    // Make sure the backup dir exists
    CreateDirectory( g_ROMBackupPath, NULL );

	CopyFile( oldpicPath.c_str(), newpicPath.c_str(), FALSE );
	CopyFile( oldvidPath.c_str(), newvidPath.c_str(), FALSE );

    PRINTMSG(( T_INFO, "Moving ROM %s to %s!", oldPath.c_str(), newPath.c_str() ));

      // For some reason MoveFile seems to fail if I move from one partition to
      // another. For this reason, do a copy & delete
//    if( !MoveFile( oldPath.c_str(), newPath.c_str() ) )
    if( !CopyFile( oldPath.c_str(), newPath.c_str(), FALSE ) )
      PRINTMSG(( T_ERROR, "Failed moving ROM %s to %s!", oldPath.c_str(), newPath.c_str() ));
    else
    {
      DeleteFile( oldPath.c_str() );
	  DeleteFile( oldpicPath.c_str() );
	  DeleteFile( oldvidPath.c_str() );
    	RemoveCurrentGameIndex();
      return TRUE;
    }
  }

  return FALSE;
}


//---------------------------------------------------------------------
//	GenerateSuperscrollJumpTable
//---------------------------------------------------------------------
void CROMListScreen::GenerateSuperscrollJumpTable( void )
{
    // Invalidate the jump table
  m_superscrollJumpTable.clear();
  m_currentSuperscrollIndex = 0;

  CStdString lastVal = "", curVal = "";
  for( UINT32 i = 0; i < m_currentSortedList.size(); ++i )
  {
      // Get the superscroll string for the current ROM
    GetFriendlySuperscrollIndexStringForROM( &curVal, i );

      // If the value is different from the last one, add the
      // index to the table
    if( lastVal != curVal )
    {
      lastVal = curVal;
      m_superscrollJumpTable.push_back( i );
    }
  }
}

//---------------------------------------------------------------------
//	UpdateSortedList // Kenny
//---------------------------------------------------------------------
void CROMListScreen::UpdateSortedList( void )
{
  UINT32 oldDriverIndex = GetCurrentGameIndex();



  if( g_romListOptions.m_fav )
  {
m_options.m_hideFiltered = TRUE;
  }


   if( !m_options.m_hideFiltered )
    m_currentSortedList = m_ROMListFull;
  else
  {
      // Reapply the filter
    UpdateFilteredList();
    m_currentSortedList = m_ROMListFiltered;
    if ( m_currentSortedList.size() == 0 ) // Kenny
	{
		 g_romListOptions.m_fav = FALSE;
		 m_options.m_hideFiltered = FALSE;
		 m_currentSortedList = m_ROMListFull;
		SaveOptions();
		UpdateSortedList();
	}
  }

    // Sort the list
  switch( m_options.m_sortMode )
  {
    // *** SM_BYNAME *** //
  default:
  case SM_BYNAME:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_Description );
    break;

    // *** SM_BYMANUFACTURER *** //
  case SM_BYMANUFACTURER:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_Manufacturer );
    break;

    // *** SM_BYYEAR *** //
  case SM_BYYEAR:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_Year );
    break;

    // *** SM_BYPARENT *** //
  case SM_BYPARENT:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_ParentROM );
    break;

    // *** SM_BYGENRE *** //
  case SM_BYGENRE:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_Genre );
    break;

    // *** SM_BYNUMPLAYERS *** //
  case SM_BYNUMPLAYERS:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_NumPlayers );
    break;

    // *** SM_BYROMSTATUS *** //
  case SM_BYROMSTATUS:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_ROMStatus );
    break;

    // *** SM_BYFAVORITESTATUS *** //
  case SM_BYFAVORITESTATUS:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_FavoriteStatus );
    break;

    // *** SM_BYNUMTIMESPLAYED *** //
  case SM_BYNUMTIMESPLAYED:
    std::stable_sort( m_currentSortedList.begin(), m_currentSortedList.end(), Compare_NumTimesPlayed );
    break;
  }

    // Ken Attempt to find the ROM that the user was on in the old sort mode
    // in the new sort mode. If it can't be found, leave the cursor alone
    // if it's less than the list size, or force it to the end of the
    // list otherwise
  if( oldDriverIndex != INVALID_ROM_INDEX )
  {
    UINT32 pos = 0;
    std::vector<UINT32>::iterator i = m_currentSortedList.begin();
    for( ; i != m_currentSortedList.end() && (*i) != oldDriverIndex; ++i, ++pos )
      ;
    if( i != m_currentSortedList.end() )
      SetAbsoluteCursorPosition( pos );
    else
      SetAbsoluteCursorPosition( 0 );
  }
  
    // Generate the superscroll table from the new list
  GenerateSuperscrollJumpTable();

    // Reposition the superscroll cursor in the new table
  if( GetCurrentGameIndex() != INVALID_ROM_INDEX )
  {
    CStdString currentString;
    GetFriendlySuperscrollIndexStringForROM( &currentString, GetAbsoluteCursorPosition() );

    UINT32 &curIDX = m_currentSuperscrollIndex;
    for( curIDX = 0; curIDX < m_superscrollJumpTable.size(); ++curIDX )
    {
      CStdString indexString;
      GetFriendlySuperscrollIndexStringForJumpTableIndex( &indexString, curIDX );

      if( indexString == currentString )
        break;
    }
  }
}

//---------------------------------------------------------------------
//  UpdateFilteredList
//---------------------------------------------------------------------
void CROMListScreen::UpdateFilteredList( void )
{
  m_ROMListFiltered.clear();

  std::vector<UINT32>::iterator i = m_ROMListFull.begin();
  for( ; i != m_ROMListFull.end(); ++i )
  {
    MAMEDriverData_t        &driverData = m_driverInfoList[*i];
    ROMStatus               &driverStatus = m_ROMStatus[*i];
    MAMEoXDriverMetadata_t  &metadata = m_driverMetadata[*i];

      // Filter on CLONE status
    if( m_options.m_filterMode & FM_CLONE &&driverData.m_isClone )
      continue;

      // Filter on the number of players
//    if( m_options.m_filterMode & FM_NUMPLAYERS && driverData.m_numPlayers < m_options.m_numPlayersFilter )
//      continue;

      // Filter on the genre



    if( m_options.m_filterMode & FM_GENRE )
    {
    }

      // Filter out ROMs marked as "SLOW"
    if( m_options.m_filterMode & FM_ROMSTATUS_SLOW && driverStatus == STATUS_SLOW )
      continue;

      // Filter out ROMs marked as "Out of memory"
    if(( !g_romListOptions.m_top && driverStatus == STATUS_OUT_OF_MEMORY && (metadata.m_favoriteStatus != FS_STRONGLIKE )) && !g_romListOptions.m_hot)
      continue;

      // Filter out ROMs marked as "Crash"
    if( !g_romListOptions.m_hot && driverStatus == STATUS_CRASH  && (metadata.m_favoriteStatus != FS_STRONGLIKE ))
      continue;

      // Filter out ROMs marked as "Other nonworking"
    if( !g_romListOptions.m_hot && driverStatus == STATUS_GENERAL_NONWORKING && (metadata.m_favoriteStatus != FS_STRONGLIKE ))
      continue;

	    if( !g_romListOptions.m_hot && driverStatus == STATUS_WORKING && (metadata.m_favoriteStatus != FS_STRONGLIKE ))
      continue;

      //Ebs filter out all roms that aren't set to 'favourite'
    if((((( m_options.m_filterMode & FM_DISLIKED && (metadata.m_favoriteStatus != FS_STRONGLIKE ) ) && driverStatus != STATUS_OUT_OF_MEMORY) && driverStatus != STATUS_GENERAL_NONWORKING) && driverStatus != STATUS_CRASH && driverStatus != STATUS_WORKING))
//Ebsfave old code    if( m_options.m_filterMode & FM_DISLIKED && (metadata.m_favoriteStatus == FS_STRONGDISLIKE || metadata.m_favoriteStatus == FS_DISLIKE) )
      continue;

//     Filter out working ROMs (for debugging/testing or screwy people)
//   if( g_romListOptions.m_top && g_romListOptions.m_hot && driverStatus == STATUS_WORKING )
//    continue;

    m_ROMListFiltered.push_back( *i );
  }
}

//---------------------------------------------------------------------
//  SetAbsoluteCursorPosition
//---------------------------------------------------------------------
void CROMListScreen::SetAbsoluteCursorPosition( UINT32 pos )
{
  if( pos == INVALID_ROM_INDEX )
    return;

	const CSkinScrollArea *area = g_loadedSkin->GetSkinElementScrollArea( SKINELEMENT_HELPSCREEN_BODY_SCROLLAREA );
	if( area )
		m_maxPageSize = area->GetHeight() / area->m_singleRowHeight;
	else
		m_maxPageSize = 15;


    // Jump the cursor to the selected position
	UINT32 pageSize = m_currentSortedList.size() < m_maxPageSize ? m_currentSortedList.size() : m_maxPageSize;
	UINT32 pageHalfwayPoint = (pageSize >> 1);
	UINT32 maxPageOffset = m_currentSortedList.size() - pageSize;

    // Put the page offset at absoluteCursorPos - pageHalwayPoint, or 0
  if( pos <= pageHalfwayPoint || m_currentSortedList.size() < m_maxPageSize )
  {
    m_pageOffset = 0.0f;
    m_cursorPosition = (FLOAT)pos;
  }
  else if( pos - pageHalfwayPoint > maxPageOffset )
  {
    m_pageOffset = maxPageOffset;
    m_cursorPosition = pos - maxPageOffset;
  }
  else
  {
    m_pageOffset = (FLOAT)(pos - pageHalfwayPoint);
    m_cursorPosition = (FLOAT)pageHalfwayPoint;
  }
}

//---------------------------------------------------------------------
//  GetFriendlySuperscrollIndexStringForJumpTableIndex
//---------------------------------------------------------------------
void CROMListScreen::GetFriendlySuperscrollIndexStringForJumpTableIndex( CStdString *ret, UINT32 superscrollTableIndex )
{
  UINT32 jumpIndex;

  assert( ret );
  if( superscrollTableIndex >= m_superscrollJumpTable.size() || 
      (jumpIndex = m_superscrollJumpTable[superscrollTableIndex]) == INVALID_ROM_INDEX )
  {
    *ret = " Scan Your Games ";
    return;
  }

  GetFriendlySuperscrollIndexStringForROM( ret, jumpIndex );
}

//---------------------------------------------------------------------
//  GetFriendlySuperscrollIndexValue
//---------------------------------------------------------------------
void CROMListScreen::GetFriendlySuperscrollIndexStringForROM( CStdString *ret, UINT32 sortedListIndex )
{
  UINT32 romIndex;
  if( sortedListIndex >= m_currentSortedList.size() || 
      (romIndex = m_currentSortedList[sortedListIndex]) == INVALID_ROM_INDEX )
  {
    *ret = "Invalid";
    return;
  }

  MAMEDriverData_t        &driver = m_driverInfoList[romIndex];
  ROMStatus               &status = m_ROMStatus[romIndex];
  MAMEoXDriverMetadata_t  &metadata = m_driverMetadata[romIndex];

  switch( m_options.m_sortMode )
  {
    // *** SM_BYNAME *** //
  case SM_BYNAME:
  default:
    {
	  char bufer[2] = {0};
      bufer[0] = toupper( driver.m_year[0] );
	  bufer[1] = toupper( driver.m_year[1] );
      char buf[12] = {0};
      buf[0] = toupper( driver.m_description[0] );

      if( !(buf[0] >= 'A' && buf[0] <= 'Z') )
        buf[0] = '#';


	  if (g_romListOptions.m_namegrouping == TRUE)
	{
	    buf[7] = toupper( driver.m_description[0] );

      if( !(buf[7] >= 'A' && buf[7] <= 'Z') )
	  {
        buf[7] = '#';
	  }
		buf[0] = 'A';
		buf[1] = 'r';
		buf[2] = 'c';
		buf[3] = 'a';
		buf[4] = 'd';
		buf[5] = 'e';
		buf[6] = ' ';
		buf[8] = '\0';
		buf[9] = '\0';
		buf[10] = '\0';
	}

 	    
	 if ((bufer[0] == 'H') && (g_romListOptions.m_namegrouping == TRUE))
	{
	    buf[5] = toupper( driver.m_description[0] );

      if( !(buf[5] >= 'A' && buf[5] <= 'Z') )
	  {
        buf[5] = '#';
	  }
		buf[0] = 'H';
		buf[1] = 'o';
		buf[2] = 'm';
		buf[3] = 'e';
		buf[4] = ' ';
		buf[6] = '\0';
		buf[7] = '\0';
		buf[8] = '\0';
		buf[9] = '\0';
		buf[10] = '\0';
	}
      *ret = buf;
    }
    break;

    // *** SM_BYMANUFACTURER *** //
  case SM_BYMANUFACTURER:
    if( driver.m_manufacturer && driver.m_manufacturer[0] )
      *ret = driver.m_manufacturer;
    else
      *ret = " Other ";
    break;

    // *** SM_BYYEAR *** //
  case SM_BYYEAR:
	  {
      char tempat[5] = {0};
	  char buferr[1] = {0};
      buferr[0] = toupper( driver.m_year[0] );

		if(buferr[0] == 'H')
			{
		tempat[0] = 'H';
		tempat[1] = 'o';
		tempat[2] = 'm';
		tempat[3] = 'e';
		tempat[4] = '\0';
		      *ret = tempat;
			} 
    else
      *ret = driver.m_year;
	  }
    break;

    // *** SM_BYPARENT *** //
  case SM_BYPARENT:
    {
   char bufer[1] = {0};
      bufer[0] = toupper( driver.m_year[0] );

      if (bufer[0] == 'H')
       *ret = " Home ";
	  else
		  *ret = " Arcade ";
	  }
    break;

    // *** SM_BYGENRE *** //
  case SM_BYGENRE:
    if( metadata.m_genre )
      *ret = metadata.m_genre;    
    else
      *ret = " Scan Your Games ";
    break;

    // *** SM_BYNUMPLAYERS *** //
  case SM_BYNUMPLAYERS:
    {
	  char bufer[1] = {0};
      char tempBuf[5] = {0};
      bufer[0] = toupper( driver.m_year[0] );
	  sprintf( tempBuf, "%lu", driver.m_numPlayers );

		if(tempBuf[0] == '0')
			{
		tempBuf[0] = '2';
		tempBuf[1] = '\0';
		tempBuf[2] = '\0';
		tempBuf[3] = '\0';
		tempBuf[4] = '\0';
			} 
		if(tempBuf[0] == '1')
			{
		tempBuf[0] = '1';
		tempBuf[1] = '\0';
		tempBuf[2] = '\0';
		tempBuf[3] = '\0';
		tempBuf[4] = '\0';
			} 
		if(tempBuf[0] == '2')
			{
		tempBuf[0] = '2';
		tempBuf[1] = '\0';
		tempBuf[2] = '\0';
		tempBuf[3] = '\0';
		tempBuf[4] = '\0';
			} 
		if(tempBuf[0] == '3')
			{
		tempBuf[0] = '3';
		tempBuf[1] = '\0';
		tempBuf[2] = '\0';
		tempBuf[3] = '\0';
		tempBuf[4] = '\0';
			} 
		if(tempBuf[0] == '4')
			{
		tempBuf[0] = '4';
		tempBuf[1] = '\0';
		tempBuf[2] = '\0';
		tempBuf[3] = '\0';
		tempBuf[4] = '\0';
			} 
		if(tempBuf[0] == '0')
			{
		tempBuf[0] = '2';
		tempBuf[1] = '\0';
		tempBuf[2] = '\0';
		tempBuf[3] = '\0';
		tempBuf[4] = '\0';
			} 
		if(bufer[0] == 'H')
			{
		tempBuf[0] = 'H';
		tempBuf[1] = 'o';
		tempBuf[2] = 'm';
		tempBuf[3] = 'e';
		tempBuf[4] = '\0';
			} 

*ret = tempBuf;
    }
    break;

    // *** SM_BYROMSTATUS *** //
  case SM_BYROMSTATUS:
       {
    char buferss[4] = {0};
      buferss[0] = toupper( driver.m_romFileName[0] );
	  buferss[1] = toupper( driver.m_romFileName[1] );
	  buferss[2] = toupper( driver.m_romFileName[2] );
	  buferss[3] = toupper( driver.m_romFileName[3] );


if ((buferss[0] == 'S') && (buferss[1] == 'N')&& (buferss[2] == 'E')&& (buferss[3] == 'S'))
       *ret = " Super Nintendo ";
else if ((buferss[0] == 'M') && (buferss[1] == 'D')&& (buferss[2] == 'R')&& (buferss[3] == 'I'))
       *ret = " Megadrive ";
else if ((buferss[0] == 'N') && (buferss[1] == '6')&& (buferss[2] == '4')&& (buferss[3] == '_'))
       *ret = " Nintendo 64 ";
else if ((buferss[0] == 'P') && (buferss[1] == 'C')&& (buferss[2] == 'E')&& (buferss[3] == '_'))
       *ret = " PC Engine ";
else if ((buferss[0] == 'P') && (buferss[1] == 'C')&& (buferss[2] == 'D')&& (buferss[3] == '_'))
       *ret = " PC Engine ";
       //*ret = " PC Engine CD ";
else if ((buferss[0] == 'N') && (buferss[1] == 'E')&& (buferss[2] == 'S')&& (buferss[3] == '_'))
       *ret = " NES ";
else if ((buferss[0] == 'S') && (buferss[1] == 'M')&& (buferss[2] == 'S')&& (buferss[3] == '_'))
       *ret = " Master System ";
else if ((buferss[0] == 'C') && (buferss[1] == '6')&& (buferss[2] == '4')&& (buferss[3] == '_'))
       *ret = " Commodore 64 ";
else if ((buferss[0] == 'X') && (buferss[1] == 'B')&& (buferss[2] == 'O')&& (buferss[3] == 'X'))
       *ret = " XBOX ";
else if ((buferss[0] == 'G') && (buferss[1] == 'B')&& (buferss[2] == 'A')&& (buferss[3] == '_'))
       *ret = " Gameboy Advance ";
else if ((buferss[0] == 'G') && (buferss[1] == 'B')&& (buferss[2] == 'C')&& (buferss[3] == '_'))
       *ret = " Gameboy Color ";
else if ((buferss[0] == 'G') && (buferss[1] == 'B')&& (buferss[2] == '_'))
       *ret = " Gameboy ";
else if ((buferss[0] == 'L') && (buferss[1] == 'Y')&& (buferss[2] == 'N')&& (buferss[3] == 'X'))
       *ret = " Atari Lynx ";
else if ((buferss[0] == 'P') && (buferss[1] == 'S')&& (buferss[2] == 'X')&& (buferss[3] == '_'))
       *ret = " Playstation ";
else if ((buferss[0] == 'G') && (buferss[1] == 'G')&& (buferss[2] == '_'))
       *ret = " Game Gear ";
else if ((buferss[0] == 'S') && (buferss[1] == 'G')&& (buferss[2] == '_'))
       *ret = " Sega SG-1000 ";
else
		  *ret = " Arcade ";
	  }
    break;


    // *** SM_BYFAVORITESTATUS *** //
  case SM_BYFAVORITESTATUS:
    switch( metadata.m_favoriteStatus )
    {
    case FS_INDIFFERENT:
      *ret = "Average";
      break;

    case FS_STRONGDISLIKE:
      *ret = "Strongly disliked";
      break;

    case FS_DISLIKE:
      *ret = "Disliked";
      break;

    case FS_LIKE:
      *ret = "Liked";
      break;

    case FS_STRONGLIKE:
		//Ebsfave changed Strongly Liked to Favourite
      *ret = "Favorite";
      break;
    }
    break;

    // *** SM_BYNUMTIMESPLAYED *** //
  case SM_BYNUMTIMESPLAYED:
    {
      char tempBuf[32] = {0};
      sprintf( tempBuf, "%lu", metadata.m_timesPlayed );
      *ret = tempBuf;
    }
    break;
  }
}

//---------------------------------------------------------------------
//  Compare_Description // Ken
//---------------------------------------------------------------------
static BOOL Compare_Description( UINT32 a, UINT32 b )
{
  MAMEDriverData_t &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t &bDriver = CROMListScreen::m_driverInfoList[b];

  int abuf = 0;
  int bbuf = 0;

    char bufers[4] = {0};
    bufers[0] = toupper( aDriver.m_year[0] );
	bufers[1] = toupper( bDriver.m_year[0] );


	abuf = 0;
	bbuf = 0;


		if ((bufers[0] == 'H') && (g_romListOptions.m_namegrouping == TRUE))
	{
		abuf = 1;
	}
	if ((bufers[1] == 'H') && (g_romListOptions.m_namegrouping == TRUE))
	{
		bbuf = 1;
	}

	int cmp = abuf - bbuf;

  if( !cmp )


  cmp = stricmp( aDriver.m_description, bDriver.m_description );

  return cmp < 0;
}


//---------------------------------------------------------------------
//  Compare_Manufacturer
//---------------------------------------------------------------------
static BOOL Compare_Manufacturer( UINT32 a, UINT32 b )
{
  MAMEDriverData_t &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t &bDriver = CROMListScreen::m_driverInfoList[b];

    // Compare the manufacturer string, sorting by name if they're equal
  int cmp = stricmp( aDriver.m_manufacturer, bDriver.m_manufacturer );
  if( !cmp )
    cmp = stricmp( aDriver.m_description, bDriver.m_description );

  return cmp < 0;
}

//---------------------------------------------------------------------
//  Compare_Year
//---------------------------------------------------------------------
static BOOL Compare_Year( UINT32 a, UINT32 b )
{
  MAMEDriverData_t &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t &bDriver = CROMListScreen::m_driverInfoList[b];

    // Compare the year string, sorting by name if they're equal
  int cmp = stricmp( aDriver.m_year, bDriver.m_year );
  if( !cmp )
    cmp = stricmp( aDriver.m_description, bDriver.m_description );

  return cmp < 0;
}

//---------------------------------------------------------------------
//  Compare_ParentROM
//---------------------------------------------------------------------
static BOOL Compare_ParentROM( UINT32 a, UINT32 b )
{
  MAMEDriverData_t &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t &bDriver = CROMListScreen::m_driverInfoList[b];
  char bufers[4] = {0};
  int abuf = 0;
  int bbuf = 0;
      bufers[0] = toupper( aDriver.m_year[0] );
	  bufers[1] = toupper( bDriver.m_year[0] );

abuf = 0;
bbuf = 0;
if (bufers[0] == 'H')
	{
		abuf = 1;
	}
	if (bufers[1] == 'H')
	{
		bbuf = 1;
	}
	

 int cmp = abuf - bbuf;
  if( !cmp )
    cmp = stricmp( aDriver.m_description, bDriver.m_description );

  return cmp < 0;
}


//---------------------------------------------------------------------
//  Compare_Genre
//---------------------------------------------------------------------
static BOOL Compare_Genre( UINT32 a, UINT32 b )
{
  MAMEDriverData_t &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t &bDriver = CROMListScreen::m_driverInfoList[b];
  MAMEoXDriverMetadata_t  &aStatus = CROMListScreen::m_driverMetadata[a];
  MAMEoXDriverMetadata_t  &bStatus = CROMListScreen::m_driverMetadata[b];

  int cmp = 0;
  if( aStatus.m_genre && bStatus.m_genre )
    cmp = stricmp( aStatus.m_genre, bStatus.m_genre );
  if( !cmp )
    cmp = stricmp( aDriver.m_description, bDriver.m_description );

  return cmp < 0;
}

//---------------------------------------------------------------------
//  Compare_NumPlayers
//---------------------------------------------------------------------
static BOOL Compare_NumPlayers( UINT32 a, UINT32 b )
{
  MAMEDriverData_t &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t &bDriver = CROMListScreen::m_driverInfoList[b];


  
      char bufer[2] = {0};
      char tempBuf[2] = {0};
	  bufer[0] = aDriver.m_numPlayers;
	  bufer[1] = bDriver.m_numPlayers;
	  tempBuf[0] = aDriver.m_year[0];
	  tempBuf[1] = bDriver.m_year[0];


  int abuff = 0;
  int bbuff = 0;

		if(tempBuf[0] == 'H')
			{
		abuff = 5;
			} 
		else if (bufer[0] == 0)
			{
		abuff = 2;
			} 
		else if(bufer[0] == 1)
			{
		abuff = 1;
			} 
		else if(bufer[0] == 2)
			{
		abuff = 2;
			} 
		else if(bufer[0] == 3)
			{
        abuff = 3;
			} 
		else if(bufer[0] == 4)
			{
		abuff = 4;
			} 
			else
		    {
		abuff = 0;
			} 


		if(tempBuf[1] == 'H')
			{
		bbuff = 5;
			} 
	    else if(bufer[1] == 0)
			{
		bbuff = 2;
			} 
		else if(bufer[1] == 1)
			{
		bbuff = 1;
			} 
		else if(bufer[1] == 2)
			{
		bbuff = 2;
			} 
		else if(bufer[1] == 3)
			{
        bbuff = 3;
			} 
		else if(bufer[1] == 4)
			{
		bbuff = 4;
			} 
		else
		    {
		bbuff = 0;
			} 
  

 int cmp = abuff - bbuff;
  if( !cmp )
    cmp = stricmp( aDriver.m_description, bDriver.m_description );

  return cmp < 0;
}

//---------------------------------------------------------------------
//  Compare_ROMStatus
//---------------------------------------------------------------------
static BOOL Compare_ROMStatus( UINT32 a, UINT32 b )
{
 MAMEDriverData_t &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t &bDriver = CROMListScreen::m_driverInfoList[b];
  char bufers[8] = {0};
  int abuff = 0;
  int bbuff = 0;
      bufers[0] = toupper( aDriver.m_romFileName[0] );
	  bufers[1] = toupper( aDriver.m_romFileName[1] );
	  bufers[2] = toupper( aDriver.m_romFileName[2] );
	  bufers[3] = toupper( aDriver.m_romFileName[3] );
	  bufers[4] = toupper( bDriver.m_romFileName[0] );
	  bufers[5] = toupper( bDriver.m_romFileName[1] );
	  bufers[6] = toupper( bDriver.m_romFileName[2] );
	  bufers[7] = toupper( bDriver.m_romFileName[3] );

if ((bufers[0] == 'S') && (bufers[1] == 'N')&& (bufers[2] == 'E')&& (bufers[3] == 'S'))
abuff = 15;
else if ((bufers[0] == 'M') && (bufers[1] == 'D')&& (bufers[2] == 'R')&& (bufers[3] == 'I'))
abuff = 8;
else if ((bufers[0] == 'N') && (bufers[1] == '6')&& (bufers[2] == '4')&& (bufers[3] == '_'))
abuff = 10;
else if ((bufers[0] == 'P') && (bufers[1] == 'C')&& (bufers[2] == 'E')&& (bufers[3] == '_'))
abuff = 11;
else if ((bufers[0] == 'P') && (bufers[1] == 'C')&& (bufers[2] == 'D')&& (bufers[3] == '_'))
//abuff = 12;
abuff = 11;
else if ((bufers[0] == 'N') && (bufers[1] == 'E')&& (bufers[2] == 'S')&& (bufers[3] == '_'))
abuff = 9;
else if ((bufers[0] == 'S') && (bufers[1] == 'M')&& (bufers[2] == 'S')&& (bufers[3] == '_'))
abuff = 7;
else if ((bufers[0] == 'C') && (bufers[1] == '6')&& (bufers[2] == '4')&& (bufers[3] == '_'))
abuff = 2;
else if ((bufers[0] == 'X') && (bufers[1] == 'B')&& (bufers[2] == 'O')&& (bufers[3] == 'X'))
abuff = 16;
else if ((bufers[0] == 'G') && (bufers[1] == 'B')&& (bufers[2] == 'A')&& (bufers[3] == '_'))
abuff = 5;
else if ((bufers[0] == 'G') && (bufers[1] == 'B')&& (bufers[2] == 'C')&& (bufers[3] == '_'))
abuff = 6;
else if ((bufers[0] == 'G') && (bufers[1] == 'B')&& (bufers[2] == '_'))
abuff = 4;
else if ((bufers[0] == 'L') && (bufers[1] == 'Y')&& (bufers[2] == 'N')&& (bufers[3] == 'X'))
abuff = 1;
else if ((bufers[0] == 'G') && (bufers[1] == 'G')&& (bufers[2] == '_'))
abuff = 3;
else if ((bufers[0] == 'S') && (bufers[1] == 'G')&& (bufers[2] == '_'))
abuff = 14;
else if ((bufers[0] == 'P') && (bufers[1] == 'S')&& (bufers[2] == 'X')&& (bufers[3] == '_'))
abuff = 13;
else
abuff = 0;

if ((bufers[4] == 'S') && (bufers[5] == 'N')&& (bufers[6] == 'E')&& (bufers[7] == 'S'))
bbuff = 15;
else if ((bufers[4] == 'M') && (bufers[5] == 'D')&& (bufers[6] == 'R')&& (bufers[7] == 'I'))
bbuff = 8;
else if ((bufers[4] == 'N') && (bufers[5] == '6')&& (bufers[6] == '4')&& (bufers[7] == '_'))
bbuff = 10;
else if ((bufers[4] == 'P') && (bufers[5] == 'C')&& (bufers[6] == 'E')&& (bufers[7] == '_'))
bbuff = 11;
else if ((bufers[4] == 'P') && (bufers[5] == 'C')&& (bufers[6] == 'D')&& (bufers[7] == '_'))
//bbuff = 12;
bbuff = 11;
else if ((bufers[4] == 'N') && (bufers[5] == 'E')&& (bufers[6] == 'S')&& (bufers[7] == '_'))
bbuff = 9;
else if ((bufers[4] == 'S') && (bufers[5] == 'M')&& (bufers[6] == 'S')&& (bufers[7] == '_'))
bbuff = 7;
else if ((bufers[4] == 'C') && (bufers[5] == '6')&& (bufers[6] == '4')&& (bufers[7] == '_'))
bbuff = 2;
else if ((bufers[4] == 'X') && (bufers[5] == 'B')&& (bufers[6] == 'O')&& (bufers[7] == 'X'))
bbuff = 16;
else if ((bufers[4] == 'G') && (bufers[5] == 'B')&& (bufers[6] == 'A')&& (bufers[7] == '_'))
bbuff = 5;
else if ((bufers[4] == 'G') && (bufers[5] == 'B')&& (bufers[6] == 'C')&& (bufers[7] == '_'))
bbuff = 6;
else if ((bufers[4] == 'G') && (bufers[5] == 'B')&& (bufers[6] == '_'))
bbuff = 4;
else if ((bufers[4] == 'L') && (bufers[5] == 'Y')&& (bufers[6] == 'N')&& (bufers[7] == 'X'))
bbuff = 1;
else if ((bufers[4] == 'G') && (bufers[5] == 'G')&& (bufers[6] == '_'))
bbuff = 3;
else if ((bufers[4] == 'S') && (bufers[5] == 'G')&& (bufers[6] == '_'))
bbuff = 14;
else if ((bufers[4] == 'P') && (bufers[5] == 'S')&& (bufers[6] == 'X')&& (bufers[7] == '_'))
bbuff = 13;
else
bbuff = 0;

 int cmp = abuff - bbuff;
  if( !cmp )
    cmp = stricmp( aDriver.m_description, bDriver.m_description );

  return cmp < 0;
}

//---------------------------------------------------------------------
//  Compare_NumTimesPlayed
//---------------------------------------------------------------------
static BOOL Compare_NumTimesPlayed( UINT32 a, UINT32 b )
{
  MAMEDriverData_t        &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t        &bDriver = CROMListScreen::m_driverInfoList[b];
  MAMEoXDriverMetadata_t  &aStatus = CROMListScreen::m_driverMetadata[a];
  MAMEoXDriverMetadata_t  &bStatus = CROMListScreen::m_driverMetadata[b];

    // Sort by the rom status, putting higher (more often played) numbers first
  int cmp = bStatus.m_timesPlayed - aStatus.m_timesPlayed;
  if( !cmp )
    return stricmp( aDriver.m_description, bDriver.m_description ) < 0;

  return cmp < 0;
}

//---------------------------------------------------------------------
//  Compare_FavoriteStatus
//---------------------------------------------------------------------
static BOOL Compare_FavoriteStatus( UINT32 a, UINT32 b )
{
  MAMEDriverData_t        &aDriver = CROMListScreen::m_driverInfoList[a];
  MAMEDriverData_t        &bDriver = CROMListScreen::m_driverInfoList[b];
  MAMEoXDriverMetadata_t  &aStatus = CROMListScreen::m_driverMetadata[a];
  MAMEoXDriverMetadata_t  &bStatus = CROMListScreen::m_driverMetadata[b];

    // Sort by the rom favorite status, putting better rated first
  if( aStatus.m_favoriteStatus != bStatus.m_favoriteStatus )
  {
      // Hack because 0 is actually neutral
    UINT32 aNumericStatus, bNumericStatus;
    switch( aStatus.m_favoriteStatus )
    {

		//Ebs favourite look
    case FS_STRONGDISLIKE:
      aNumericStatus = 0;
      break;
    case FS_DISLIKE:
      aNumericStatus = 1;
      break;
    default:
    case FS_INDIFFERENT:
      aNumericStatus = 2;
      break;
    case FS_LIKE:
      aNumericStatus = 3;
      break;
    case FS_STRONGLIKE:
      aNumericStatus = 4;
      break;
    }

    switch( bStatus.m_favoriteStatus )
    {
    case FS_STRONGDISLIKE:
      bNumericStatus = 0;
      break;
    case FS_DISLIKE:
      bNumericStatus = 1;
      break;
    default:
    case FS_INDIFFERENT:
      bNumericStatus = 2;
      break;
    case FS_LIKE:
      bNumericStatus = 3;
      break;
    case FS_STRONGLIKE:
      bNumericStatus = 4;
      break;
    }

    return bNumericStatus < aNumericStatus;
  }
  
  return stricmp( aDriver.m_description, bDriver.m_description ) < 0;
}

//---------------------------------------------------------------------
//  Helper_ReadXMLTag
//---------------------------------------------------------------------
static BOOL Helper_ReadXMLTag( osd_file *file, CStdString *tagName )
{
  char buffer[2] = {0};
  if( !tagName )
    return FALSE;

  *tagName = "<";
  while( osd_fread( file, buffer, 1 ) && buffer[0] != '>' )
  {
    buffer[0] = tolower( buffer[0] );
    if( buffer[0] != '\n' && buffer[0] != '\r' )
      *tagName += buffer;
  }

    // Did we find the end of the tag?
  if( buffer[0] != '>' )
    return FALSE;

    // Cat on the tag end
  *tagName += ">";
  return TRUE;
}




